from folkugat_web.dal.sql import Connection, get_connection


def create_db(con: Connection | None = None):
    with get_connection(con) as con:
        create_sessions_table(con)
        create_session_playlists_table(con)


def create_sessions_table(con: Connection):
    query = """
      CREATE TABLE IF NOT EXISTS sessions (
        id INTEGER PRIMARY KEY,
        date TEXT NOT NULL,
        start_time TEXT NOT NULL,
        end_time TEXT NOT NULL,
        venue_name TEXT,
        venue_url TEXT,
        notes TEXT,
        cartell_url TEXT,
        is_live BOOLEAN DEFAULT false
    )
    """
    cur = con.cursor()
    _ = cur.execute(query)


def create_session_playlists_table(con: Connection):
    query = """
      CREATE TABLE IF NOT EXISTS session_playlists (
        session_id INTEGER,
        playlist_type TEXT,
        playlist_id INTEGER NOT NULL,
        PRIMARY KEY (session_id, playlist_type),
        FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE,
        FOREIGN KEY (playlist_id) REFERENCES playlists(id) ON DELETE CASCADE
    )
    """
    cur = con.cursor()
    _ = cur.execute(query)
