import sqlite3
from dataclasses import dataclass
from typing import Optional, List

@dataclass
class ConversationModel:
    id: Optional[int] = None
    is_group: Optional[int] = None
    name: Optional[str] = None
    created_at: Optional[str] = None

class Conversations:
    def __init__(self, db_path="instance/app_database.db"):
        self.db_path = db_path
        self._create_tables()

    def _create_tables(self):
        with sqlite3.connect(self.db_path) as conn:
            cursor = conn.cursor()
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS conversations (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    is_group INTEGER DEFAULT 0,
                    name TEXT,
                    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
                );
            """)
            conn.commit()

    def create(self, is_group: int, name: Optional[str] = None) -> int:
        with sqlite3.connect(self.db_path) as conn:
            cursor = conn.cursor()
            cursor.execute(
                "INSERT INTO conversations (is_group, name) VALUES (?, ?)",
                (is_group, name)
            )
            return cursor.lastrowid

    def get_by_id(self, conv_id: int) -> Optional[ConversationModel]:
        with sqlite3.connect(self.db_path) as conn:
            conn.row_factory = sqlite3.Row
            cursor = conn.cursor()
            cursor.execute("SELECT * FROM conversations WHERE id = ?", (conv_id,))
            row = cursor.fetchone()
            return ConversationModel(**dict(row)) if row else None

    def delete(self, conv_id: int):
        with sqlite3.connect(self.db_path) as conn:
            conn.execute("DELETE FROM conversations WHERE id = ?", (conv_id,))