import uuid

from sqlalchemy.ext.asyncio import AsyncSession

from domains.notifications.models import Notification, NotificationType
from domains.notifications.repo import (
    create_notification,
    get_user_notifications,
    get_notification_by_id,
    update_notification
)

async def send_public_notification(
    db: AsyncSession,
    title: str,
    description: str,
    sender_id: uuid.UUID,
    receiver_ids: list[uuid.UUID]
):
    notifications = []
    for receiver_id in receiver_ids:
        notification = Notification(
            title=title,
            description=description,
            type=NotificationType.PUBLIC,
            sender_id=sender_id,
            receiver_id=receiver_id
        )
        db.add(notification)
        notifications.append(notification)
    
    await db.commit()
    return notifications

async def send_join_request(
    db: AsyncSession,
    sender_id: uuid.UUID,
    receiver_id: uuid.UUID,
    group_id: uuid.UUID,
    title: str,
    description: str | None = None
):
    notification = Notification(
        title=title,
        description=description,
        type=NotificationType.JOIN_REQUEST,
        sender_id=sender_id,
        receiver_id=receiver_id,
        group_id=group_id
    )
    return await create_notification(db, notification)

async def list_my_notifications(db: AsyncSession, user_id: uuid.UUID):
    return await get_user_notifications(db, user_id)

async def respond_to_notification(
    db: AsyncSession,
    notification_id: str | uuid.UUID,
    user_id: uuid.UUID,
    is_accepted: bool
):
    notification_id_uuid = notification_id if isinstance(notification_id, uuid.UUID) else uuid.UUID(notification_id)
    notification = await get_notification_by_id(db, notification_id_uuid)
    if not notification:
        raise ValueError("نوتیفیکیشنی یافت نشد")
    
    if str(notification.receiver_id) != str(user_id):
        raise ValueError("دسترسی لازم را ندارید")
    
    notification.is_accepted = is_accepted
    await update_notification(db, notification)
    
    # If it's a join request and accepted, add user to group
    if notification.type == NotificationType.JOIN_REQUEST and is_accepted:
        from domains.groups.service import add_member_to_group
        await add_member_to_group(db, notification.group_id, user_id) # type: ignore
        
    return notification
