"""Kategori DB erişimi. Her sorgu tenant_id filtreli."""
from fastapi import Depends
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.database import get_db
from app.models.product import ProductCategory


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

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

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

    async def slug_exists(
        self, tenant_id: str, slug: str, exclude_id: str | None = None
    ) -> bool:
        stmt = select(ProductCategory.id).where(
            ProductCategory.tenant_id == tenant_id,
            ProductCategory.slug == slug,
        )
        if exclude_id:
            stmt = stmt.where(ProductCategory.id != exclude_id)
        result = await self.db.execute(stmt)
        return result.scalar_one_or_none() is not None

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

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

    async def delete(self, cat: ProductCategory) -> None:
        await self.db.delete(cat)
        await self.db.commit()
