from db.database import conn, cursor


def create_promo(kode: str, kuota: int, harga: int) -> dict:
    cursor.execute("""
        INSERT OR REPLACE INTO promos (kode, kuota, terpakai, harga, type)
        VALUES (?, ?, 0, ?, 'fixed')
    """, (kode, kuota, harga))
    conn.commit()
    return get_promo(kode)


def create_promo_percent(kode: str, kuota: int, persen: int) -> dict:
    cursor.execute("""
        INSERT OR REPLACE INTO promos (kode, kuota, terpakai, persen, type)
        VALUES (?, ?, 0, ?, 'percent')
    """, (kode, kuota, persen))
    conn.commit()
    return get_promo(kode)


def get_promo(kode: str):
    cursor.execute("SELECT * FROM promos WHERE kode = ?", (kode,))
    row = cursor.fetchone()
    return dict(row) if row else None


def use_promo(kode: str) -> bool:
    cursor.execute("""
        UPDATE promos
        SET terpakai = terpakai + 1
        WHERE kode = ? AND terpakai < kuota
    """, (kode,))
    conn.commit()
    return cursor.rowcount > 0


def release_promo(kode: str):
    cursor.execute("""
        UPDATE promos SET terpakai = MAX(0, terpakai - 1) WHERE kode = ?
    """, (kode,))
    conn.commit()


def get_all_promos():
    cursor.execute("SELECT * FROM promos")
    rows = cursor.fetchall()
    return {r["kode"]: dict(r) for r in rows}
