import psycopg2.extras
from config import get_local_db_connection   # centralize DB connection

# ───────── FAVORITES ───────── #
def db_init_favorites_table():
    conn, cur = get_local_db_connection()
    cur = conn.cursor()
    cur.execute("""
        CREATE TABLE IF NOT EXISTS favorites (
            video_id UUID PRIMARY KEY,         -- better: store as uuid
            created_at TIMESTAMPTZ DEFAULT NOW()
        )
    """)
    conn.commit()
    cur.close(); conn.close()

def db_get_fav_set():
    conn, cur = get_local_db_connection()
    cur = conn.cursor()
    cur.execute("SELECT video_id FROM favorites")
    favs = {str(row[0]) for row in cur.fetchall()}
    cur.close(); conn.close()
    return favs

def db_toggle_fav(video_id: str):
    conn, cur = get_local_db_connection()
    cur = conn.cursor()
    cur.execute("DELETE FROM favorites WHERE video_id = %s", (video_id,))
    if cur.rowcount == 0:
        cur.execute("INSERT INTO favorites (video_id) VALUES (%s)", (video_id,))
        conn.commit()
        cur.close(); conn.close()
        return True   # now favorited
    conn.commit()
    cur.close(); conn.close()
    return False      # now unfavorited

def mark_favorites(videos: list[dict]):
    """Adds is_favorite: bool to each video dict in-place."""
    favs = db_get_fav_set()
    for v in videos:
        vid = str(v.get("video_id"))
        v["is_favorite"] = (vid in favs)
    return videos

def db_get_favorites(page: int, per_page: int):
    offset = (page - 1) * per_page
    conn, cur = get_local_db_connection()
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)

    cur.execute("""
        SELECT
            v.video_id, v.username, v.site AS platform,
            v.filepath, v.size, v.duration, v.gender,
            v.created_at, v.updated_at, v.thumbnail
        FROM favorites f
        JOIN videos v ON v.video_id = f.video_id
        WHERE v.status != 'missing'
        ORDER BY f.created_at DESC NULLS LAST, v.created_at DESC NULLS LAST
        LIMIT %s OFFSET %s
    """, (per_page, offset))
    rows = [dict(r) for r in cur.fetchall()]

    cur.execute("""
        SELECT COUNT(*)
        FROM favorites f
        JOIN videos v ON v.video_id = f.video_id
        WHERE v.status != 'missing'
    """)
    total = cur.fetchone()[0]

    cur.close(); conn.close()
    return rows, total