from datetime import datetime
from typing import List, Optional
from src.core.database.database import Database
from src.core.models.models import Session
from src.utils.logger import get_logger

logger = get_logger("session_dao")

class SessionDAO:
    def __init__(self, db: Database):
        self.db = db

    def create(self, name: Optional[str] = None) -> Session:
        """Создание новой сессии с именем."""
        with self.db.get_cursor() as cursor:
            cursor.execute(
                "INSERT INTO sessions (name, created_at) VALUES (?, CURRENT_TIMESTAMP) RETURNING *",
                (name,)
            )
            row = cursor.fetchone()
            return Session(
                id=row["id"],
                name=row["name"],
                created_at=datetime.fromisoformat(row["created_at"])
            )

    def get_by_id(self, session_id: int) -> Optional[Session]:
        """Получение сессии по ID."""
        with self.db.get_cursor() as cursor:
            cursor.execute("SELECT * FROM sessions WHERE id = ?", (session_id,))
            row = cursor.fetchone()
            if row:
                return Session(
                    id=row["id"],
                    name=row["name"],
                    created_at=datetime.fromisoformat(row["created_at"])
                )
            return None

    def get_all(self) -> List[Session]:
        """Получение всех сессий."""
        with self.db.get_cursor() as cursor:
            cursor.execute("SELECT * FROM sessions ORDER BY created_at ASC")
            rows = cursor.fetchall()
            return [
                Session(
                    id=row["id"],
                    name=row["name"],
                    created_at=datetime.fromisoformat(row["created_at"])
                ) for row in rows
            ]

    def delete(self, session_id: int) -> bool:
        """Удаление сессии по ID."""
        with self.db.get_cursor() as cursor:
            cursor.execute("DELETE FROM sessions WHERE id = ?", (session_id,))
            return cursor.rowcount > 0

    def update_name(self, session_id: int, name: str) -> bool:
        """Обновление имени сессии."""
        with self.db.get_cursor() as cursor:
            cursor.execute(
                "UPDATE sessions SET name = ? WHERE id = ?",
                (name, session_id)
            )
            return cursor.rowcount > 0