import discord
from utils.sql_commands import DatabaseManager
from typing import Dict
from datetime import datetime


db = DatabaseManager("economy")


async def create_account(user: discord.Member | discord.User):
    """Create a new economy account for a user."""
    db.insert(
        "INSERT INTO economy (ID, WALLET, BANK) VALUES (%s, %s, %s)", (user.id, 0, 1000)
    )


async def bank_data(user: discord.Member | discord.User) -> Dict[str, int]:
    """Get the bank data for a user. If the user has no account, create one.

    Args:
        user: The user to get the bank data for.

    Returns:
        A dictionary with the keys ``WALLET`` and ``BANK`` containing the user's wallet and bank balances.
    """
    balance = db.fetch_one("SELECT * FROM economy WHERE ID = %s", (user.id,))
    if balance is None:
        await create_account(user)
        return await bank_data(user)
    return balance


async def record_transaction(
    user_id: int, transaction_type: str, amount: float
) -> None:
    """Record a transaction in the database.

    Args:
        user_id: The ID of the user who performed the transaction.
        transaction_type: The type of transaction performed.
        amount: The amount of the transaction.
    """
    db.execute_query(
        "INSERT INTO transactions (USERID, TYPE, AMOUNT) VALUES (%s, %s, %s)",
        (user_id, transaction_type, amount),
    )


async def update_money(
    user: discord.Member | discord.User, bank: int = 0, wallet: int = 0
):
    """Update the bank balance of a user.

    Args:
        user: The user to update the balance for.
        bank: The amount to add to the user's bank balance.
        wallet: The amount to add to the user's wallet balance.

    Returns:
        A dictionary with the keys ``WALLET`` and ``BANK`` containing the updated balances.
    """
    balance = await bank_data(user)
    if bank or wallet:
        new_wallet = balance.get("WALLET", 0) + wallet
        new_bank = balance.get("BANK", 0) + bank
        db.insert(
            "INSERT INTO economy (ID, WALLET, BANK) VALUES (%s, %s, %s)",
            (user.id, new_wallet, new_bank),
            overwrite=True,
        )


async def reset_bank(user: discord.Member | discord.User) -> None:
    """Reset the bank account for a user.

    Args:
        user (discord.Member | discord.User): The user whose bank account is to be reset.

    Returns:
        None
    """
    db.delete("economy", {"ID": user.id})
    await create_account(user)


async def update_daily_timestamp(user: discord.User | discord.Member, timestamp: datetime) -> None:
    """
    Updates the DAILY_TIMESTAMP field for the user in the economy table.
    Stores the timestamp as a float (UNIX time).
    """
    db.execute_query("UPDATE economy SET DAILY = %s WHERE ID = %s",(timestamp.timestamp(), user.id),
    )
