from db.database import conn, cursor


def get_all_channels():
    cursor.execute("SELECT * FROM channels ORDER BY id")
    return [dict(r) for r in cursor.fetchall()]


def get_channel_by_id(channel_id):
    cursor.execute("SELECT * FROM channels WHERE id = ?", (int(channel_id),))
    row = cursor.fetchone()
    return dict(row) if row else None


def add_channel(name, type_, chat_id=None, username=None, link=None):
    cursor.execute("""
        INSERT INTO channels (name, type, chat_id, username, link)
        VALUES (?, ?, ?, ?, ?)
    """, (name.strip(), type_, chat_id, username, link))
    conn.commit()
    return dict(cursor.execute(
        "SELECT * FROM channels WHERE id = ?", (cursor.lastrowid,)
    ).fetchone())


def update_channel(channel_id, **kwargs):
    allowed = {"name", "chat_id", "username", "type", "link"}
    fields = {k: v for k, v in kwargs.items() if k in allowed}
    if not fields:
        return None
    fields["updated_at"] = None
    set_clause = ", ".join(f"{k} = ?" for k in fields)
    values = list(fields.values())
    cursor.execute(
        f"UPDATE channels SET {set_clause}, updated_at = datetime('now', 'localtime') WHERE id = ?",
        (*values, int(channel_id))
    )
    conn.commit()
    return get_channel_by_id(channel_id)


def delete_channel(channel_id):
    cursor.execute("DELETE FROM channels WHERE id = ?", (int(channel_id),))
    conn.commit()
    return cursor.rowcount > 0

