import uuid
from typing import Optional
from sqlalchemy import func, select, update
from sqlalchemy.ext.asyncio import AsyncSession
from modules.notifications.models import Notification


class NotificationRepository:
    def __init__(self, db: AsyncSession):
        self.db = db

    async def create(
        self,
        tenant_id: uuid.UUID,
        title: str,
        message: str,
        category: str = "system",
        action_url: Optional[str] = None,
        user_id: Optional[uuid.UUID] = None,
    ) -> Notification:
        notif = Notification(
            id=uuid.uuid4(),
            tenant_id=tenant_id,
            user_id=user_id,
            title=title,
            message=message,
            category=category,
            action_url=action_url,
            is_read=False,
        )
        self.db.add(notif)
        await self.db.commit()
        await self.db.refresh(notif)
        return notif

    async def list_by_tenant(
        self,
        tenant_id: uuid.UUID,
        unread_only: bool = False,
        limit: int = 50,
    ) -> list[Notification]:
        stmt = select(Notification).where(Notification.tenant_id == tenant_id)
        if unread_only:
            stmt = stmt.where(Notification.is_read.is_(False))
        stmt = stmt.order_by(Notification.created_at.desc()).limit(limit)
        res = await self.db.execute(stmt)
        return list(res.scalars().all())

    async def mark_read(
        self,
        tenant_id: uuid.UUID,
        notification_ids: list[uuid.UUID],
    ) -> int:
        res = await self.db.execute(
            update(Notification)
            .where(
                Notification.tenant_id == tenant_id,
                Notification.id.in_(notification_ids),
            )
            .values(is_read=True)
        )
        await self.db.commit()
        return res.rowcount or 0

    async def count_unread(self, tenant_id: uuid.UUID) -> int:
        res = await self.db.execute(
            select(func.count(Notification.id)).where(
                Notification.tenant_id == tenant_id,
                Notification.is_read.is_(False),
            )
        )
        return res.scalar() or 0
