from __future__ import annotations

from typing import Optional
from uuid import UUID, uuid4

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from src.domain.livechat.models import ProjectLivechatConfig


class LivechatRepository:
    def __init__(self, db: AsyncSession) -> None:
        self._db = db

    async def get_config(self, project_id: UUID) -> Optional[ProjectLivechatConfig]:
        return (await self._db.execute(select(ProjectLivechatConfig).where(ProjectLivechatConfig.project_id == project_id))).scalar_one_or_none()

    async def upsert_config(self, project_id: UUID, **fields: object) -> ProjectLivechatConfig:
        row = await self.get_config(project_id)
        if row is None:
            row = ProjectLivechatConfig(id=uuid4(), project_id=project_id, **fields)
            self._db.add(row)
        else:
            for key, value in fields.items():
                setattr(row, key, value)
        await self._db.flush()
        return row
