import uuid
from typing import Optional
from sqlalchemy.ext.asyncio import AsyncSession
from modules.notifications.models import Notification
from modules.notifications.repository import NotificationRepository
from modules.notifications.schemas import (
    CreateNotificationRequest,
    NotificationResponse,
)


class NotificationService:
    """Manages system, billing, and broadcast event notifications."""

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

    async def create_notification(
        self,
        tenant_id: uuid.UUID,
        req: CreateNotificationRequest,
    ) -> NotificationResponse:
        notif = await self.repo.create(
            tenant_id=tenant_id,
            title=req.title,
            message=req.message,
            category=req.category,
            action_url=req.action_url,
            user_id=req.user_id,
        )
        return NotificationResponse.model_validate(notif)

    async def list_notifications(
        self,
        tenant_id: uuid.UUID,
        unread_only: bool = False,
    ) -> list[NotificationResponse]:
        notifs = await self.repo.list_by_tenant(tenant_id, unread_only=unread_only)
        return [NotificationResponse.model_validate(n) for n in notifs]

    async def mark_notifications_read(
        self,
        tenant_id: uuid.UUID,
        notification_ids: list[uuid.UUID],
    ) -> int:
        return await self.repo.mark_read(tenant_id, notification_ids)

    async def get_unread_count(self, tenant_id: uuid.UUID) -> int:
        return await self.repo.count_unread(tenant_id)
