import sqlite3
from core.config import DB_PATH
from core.security import hash_pw


def is_setup_done() -> bool:
    db = sqlite3.connect(DB_PATH)
    db.row_factory = sqlite3.Row
    try:
        row = db.execute(
            "SELECT deger FROM ayarlar WHERE anahtar='kurulum_tamamlandi'"
        ).fetchone()
    except Exception:
        row = None
    finally:
        db.close()
    return row is not None and row['deger'] == '1'


def do_setup(db, dukkan_adi: str, parola: str) -> None:
    db.execute(
        "INSERT OR REPLACE INTO ayarlar (anahtar,deger) VALUES ('dukkan_adi',?)",
        (dukkan_adi,)
    )
    db.execute(
        "INSERT OR REPLACE INTO ayarlar (anahtar,deger) VALUES ('parola_hash',?)",
        (hash_pw(parola),)
    )
    db.execute(
        "INSERT OR REPLACE INTO ayarlar (anahtar,deger) VALUES ('kurulum_tamamlandi','1')"
    )
    db.commit()


def check_password(db, parola: str) -> bool:
    row = db.execute(
        "SELECT deger FROM ayarlar WHERE anahtar='parola_hash'"
    ).fetchone()
    return row is not None and row['deger'] == hash_pw(parola)


def get_dukkan_adi(db) -> str:
    row = db.execute(
        "SELECT deger FROM ayarlar WHERE anahtar='dukkan_adi'"
    ).fetchone()
    return row['deger'] if row else ''


def reset_password(db, yeni_parola: str) -> None:
    """Master şifre ile tetiklenen şifre sıfırlama."""
    db.execute(
        "INSERT OR REPLACE INTO ayarlar (anahtar,deger) VALUES ('parola_hash',?)",
        (hash_pw(yeni_parola),)
    )
    db.commit()
