"""Chat session + message DB erişimi. Tenant izolasyonu zorunlu."""
from fastapi import Depends
from sqlalchemy import select, update
from sqlalchemy.ext.asyncio import AsyncSession

from app.database import get_db
from app.models.chat import ChatMessage, ChatSession


class ChatRepository:
    def __init__(self, db: AsyncSession = Depends(get_db)):
        self.db = db

    # --- Sessions ---

    async def get_session(self, session_id: str, tenant_id: str) -> ChatSession | None:
        result = await self.db.execute(
            select(ChatSession).where(
                ChatSession.id == session_id,
                ChatSession.tenant_id == tenant_id,
            )
        )
        return result.scalar_one_or_none()

    async def get_session_by_token(self, token: str) -> ChatSession | None:
        result = await self.db.execute(
            select(ChatSession).where(ChatSession.session_token == token)
        )
        return result.scalar_one_or_none()

    async def list_sessions(
        self, tenant_id: str, status: str | None = None, limit: int = 50
    ) -> list[ChatSession]:
        stmt = select(ChatSession).where(ChatSession.tenant_id == tenant_id)
        if status:
            stmt = stmt.where(ChatSession.status == status)
        stmt = stmt.order_by(ChatSession.started_at.desc()).limit(limit)
        result = await self.db.execute(stmt)
        return list(result.scalars().all())

    async def create_session(self, **kwargs) -> ChatSession:
        session = ChatSession(**kwargs)
        self.db.add(session)
        await self.db.commit()
        await self.db.refresh(session)
        return session

    async def update_session(self, session: ChatSession, **kwargs) -> ChatSession:
        for key, value in kwargs.items():
            setattr(session, key, value)
        await self.db.commit()
        await self.db.refresh(session)
        return session

    async def reassign_visitor(
        self, tenant_id: str, from_visitor_id: str, to_visitor_id: str
    ) -> None:
        """Profil merge'inde oturumları kaynak ziyaretçiden hedefe taşı."""
        await self.db.execute(
            update(ChatSession)
            .where(
                ChatSession.tenant_id == tenant_id,
                ChatSession.visitor_id == from_visitor_id,
            )
            .values(visitor_id=to_visitor_id)
        )
        await self.db.commit()

    # --- Messages ---

    async def add_message(self, **kwargs) -> ChatMessage:
        msg = ChatMessage(**kwargs)
        self.db.add(msg)
        await self.db.commit()
        await self.db.refresh(msg)
        return msg

    async def list_messages(
        self, session_id: str, tenant_id: str, limit: int = 100
    ) -> list[ChatMessage]:
        result = await self.db.execute(
            select(ChatMessage)
            .where(
                ChatMessage.session_id == session_id,
                ChatMessage.tenant_id == tenant_id,
            )
            .order_by(ChatMessage.created_at.asc())
            .limit(limit)
        )
        return list(result.scalars().all())
