"""Widget DB erişimi. Panel sorguları tenant_id filtreli; api_key lookup public."""
from fastapi import Depends
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession

from app.database import get_db
from app.models.chat import ChatWidget
from app.models.product import Product


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

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

    async def get_by_api_key(self, api_key: str) -> ChatWidget | None:
        result = await self.db.execute(
            select(ChatWidget).where(ChatWidget.api_key == api_key)
        )
        return result.scalar_one_or_none()

    async def list_by_tenant(self, tenant_id: str) -> list[ChatWidget]:
        result = await self.db.execute(
            select(ChatWidget)
            .where(ChatWidget.tenant_id == tenant_id)
            .order_by(ChatWidget.created_at.desc())
        )
        return list(result.scalars().all())

    async def count_active_products(self, tenant_id: str) -> int:
        result = await self.db.execute(
            select(func.count(Product.id)).where(
                Product.tenant_id == tenant_id,
                Product.deleted_at.is_(None),
                Product.is_active.is_(True),
            )
        )
        return int(result.scalar() or 0)

    async def create(self, **kwargs) -> ChatWidget:
        widget = ChatWidget(**kwargs)
        self.db.add(widget)
        await self.db.commit()
        await self.db.refresh(widget)
        return widget

    async def update(self, widget: ChatWidget, **kwargs) -> ChatWidget:
        for key, value in kwargs.items():
            setattr(widget, key, value)
        await self.db.commit()
        await self.db.refresh(widget)
        return widget
