from folkugat_web.dal.sql import Connection, get_connection


def create_db(con: Connection | None = None):
    with get_connection(con) as con:
        create_temes_table(con)
        create_links_table(con)
        create_lyrics_table(con)
        create_properties_table(con)
        create_scores_table(con)


def create_temes_table(con: Connection):
    query = """
      CREATE TABLE IF NOT EXISTS temes (
        id INTEGER PRIMARY KEY,
        title TEXT NOT NULL,
        alternatives TEXT,
        creation_date TEXT NOT NULL,
        modification_date TEXT NOT NULL,
        hidden INTEGER NOT NULL
    )
    """
    cur = con.cursor()
    _ = cur.execute(query)


def create_links_table(con: Connection):
    query = """
      CREATE TABLE IF NOT EXISTS tema_links (
        id INTEGER PRIMARY KEY,
        tema_id INTEGER,
        content_type TEXT NOT NULL,
        link_type TEXT,
        title TEXT NOT NULL,
        url TEXT NOT NULL,
        FOREIGN KEY(tema_id) REFERENCES temes(id) ON DELETE CASCADE
    )
    """
    cur = con.cursor()
    _ = cur.execute(query)


def create_lyrics_table(con: Connection):
    query = """
      CREATE TABLE IF NOT EXISTS tema_lyrics (
        id INTEGER PRIMARY KEY,
        tema_id INTEGER,
        title TEXT NOT NULL,
        content TEXT NOT NULL,
        FOREIGN KEY(tema_id) REFERENCES temes(id) ON DELETE CASCADE
    )
    """
    cur = con.cursor()
    _ = cur.execute(query)


def create_properties_table(con: Connection):
    query = """
      CREATE TABLE IF NOT EXISTS tema_properties (
        id INTEGER PRIMARY KEY,
        tema_id INTEGER,
        field TEXT NOT NULL,
        value TEXT NOT NULL,
        FOREIGN KEY(tema_id) REFERENCES temes(id) ON DELETE CASCADE
    )
    """
    cur = con.cursor()
    _ = cur.execute(query)


def create_scores_table(con: Connection):
    query = """
      CREATE TABLE IF NOT EXISTS tema_scores (
        id INTEGER PRIMARY KEY,
        tema_id INTEGER,
        title TEXT,
        source TEXT NOT NULL,
        errors TEXT NOT NULL,
        img_url TEXT,
        pdf_url TEXT,
        preview_url TEXT,
        hidden BOOLEAN,
        FOREIGN KEY(tema_id) REFERENCES temes(id) ON DELETE CASCADE
    )
    """
    cur = con.cursor()
    _ = cur.execute(query)
