"""
Service for managing user notification history
"""
from typing import List, Optional, Dict, Any
from datetime import datetime, timezone
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, and_, func as sql_func
from sqlalchemy.orm import selectinload
from fastapi import HTTPException, status

from app.models.user.notification_model import UserNotification
from app.models.user.user_model import User


class NotificationHistoryService:
    """Service for managing user notification history"""
    
    def __init__(self, db: AsyncSession):
        self.db = db
    
    async def get_user_notifications(
        self,
        user_id: int,
        skip: int = 0,
        limit: int = 100,
        unread_only: bool = False,
        notification_type: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        Get user's notification history with pagination
        Returns notifications sorted by most recent first
        """
        # Verify user exists
        user_stmt = select(User).where(User.user_id == user_id)
        user_result = await self.db.execute(user_stmt)
        user = user_result.scalar_one_or_none()
        
        if not user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="User not found"
            )
        
        # Build query
        stmt = select(UserNotification).where(UserNotification.user_id == user_id)
        
        # Apply filters
        if unread_only:
            stmt = stmt.where(UserNotification.is_read == False)
        
        if notification_type:
            stmt = stmt.where(UserNotification.notification_type == notification_type)
        
        # Get total count
        count_stmt = select(sql_func.count(UserNotification.notification_id)).where(
            UserNotification.user_id == user_id
        )
        if unread_only:
            count_stmt = count_stmt.where(UserNotification.is_read == False)
        if notification_type:
            count_stmt = count_stmt.where(UserNotification.notification_type == notification_type)
        
        count_result = await self.db.execute(count_stmt)
        total_count = count_result.scalar()
        
        # Apply pagination and ordering (most recent first)
        stmt = stmt.order_by(UserNotification.sent_at.desc()).offset(skip).limit(limit)
        
        # Load relationships
        stmt = stmt.options(
            selectinload(UserNotification.product),
            selectinload(UserNotification.store),
            selectinload(UserNotification.listing)
        )
        
        result = await self.db.execute(stmt)
        notifications = result.scalars().all()
        
        # Format response
        notifications_list = []
        for notification in notifications:
            notifications_list.append({
                "notification_id": notification.notification_id,
                "title": notification.title,
                "body": notification.body,
                "image_url": notification.image_url,
                "notification_type": notification.notification_type,
                "data": notification.data_payload or {},
                "product_id": notification.product_id,
                "store_id": notification.store_id,
                "listing_id": notification.listing_id,
                "distance_km": notification.distance_km,
                "is_read": notification.is_read,
                "fcm_sent": notification.fcm_sent,
                "sent_at": notification.sent_at.isoformat() if notification.sent_at else None,
                "read_at": notification.read_at.isoformat() if notification.read_at else None,
                "created_at": notification.created_at.isoformat() if notification.created_at else None,
                # Include related entity details if available
                "product": {
                    "product_id": notification.product.product_id,
                    "product_name": notification.product.product_name,
                    "product_image": notification.product.product_image
                } if notification.product else None,
                "store": {
                    "store_id": notification.store.store_id,
                    "store_name": notification.store.store_name,
                    "store_location": notification.store.store_location
                } if notification.store else None
            })
        
        return {
            "notifications": notifications_list,
            "total": total_count,
            "skip": skip,
            "limit": limit,
            "unread_only": unread_only
        }
    
    async def get_unread_count(self, user_id: int) -> Dict[str, int]:
        """Get count of unread notifications for user"""
        # Verify user exists
        user_stmt = select(User).where(User.user_id == user_id)
        user_result = await self.db.execute(user_stmt)
        user = user_result.scalar_one_or_none()
        
        if not user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="User not found"
            )
        
        # Count unread notifications
        count_stmt = select(sql_func.count(UserNotification.notification_id)).where(
            and_(
                UserNotification.user_id == user_id,
                UserNotification.is_read == False
            )
        )
        
        count_result = await self.db.execute(count_stmt)
        unread_count = count_result.scalar()
        
        return {
            "unread_count": unread_count
        }
    
    async def mark_notification_as_read(
        self,
        user_id: int,
        notification_id: int
    ) -> Dict[str, Any]:
        """Mark a specific notification as read"""
        # Get notification and verify it belongs to user
        stmt = select(UserNotification).where(
            and_(
                UserNotification.notification_id == notification_id,
                UserNotification.user_id == user_id
            )
        )
        
        result = await self.db.execute(stmt)
        notification = result.scalar_one_or_none()
        
        if not notification:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Notification not found"
            )
        
        # Mark as read if not already read
        if not notification.is_read:
            notification.is_read = True
            notification.read_at = datetime.now(timezone.utc)
            await self.db.commit()
            await self.db.refresh(notification)
        
        return {
            "notification_id": notification.notification_id,
            "is_read": notification.is_read,
            "read_at": notification.read_at.isoformat() if notification.read_at else None,
            "message": "Notification marked as read"
        }
    
    async def mark_all_as_read(self, user_id: int) -> Dict[str, Any]:
        """Mark all notifications as read for user"""
        # Verify user exists
        user_stmt = select(User).where(User.user_id == user_id)
        user_result = await self.db.execute(user_stmt)
        user = user_result.scalar_one_or_none()
        
        if not user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="User not found"
            )
        
        # Update all unread notifications
        now = datetime.now(timezone.utc)
        stmt = select(UserNotification).where(
            and_(
                UserNotification.user_id == user_id,
                UserNotification.is_read == False
            )
        )
        result = await self.db.execute(stmt)
        notifications = result.scalars().all()
        
        updated_count = 0
        for notification in notifications:
            notification.is_read = True
            notification.read_at = now
            updated_count += 1
        
        await self.db.commit()
        
        return {
            "updated_count": updated_count,
            "message": f"Marked {updated_count} notification(s) as read"
        }
    
    async def delete_notification(
        self,
        user_id: int,
        notification_id: int
    ) -> Dict[str, Any]:
        """Delete a specific notification"""
        # Get notification and verify it belongs to user
        stmt = select(UserNotification).where(
            and_(
                UserNotification.notification_id == notification_id,
                UserNotification.user_id == user_id
            )
        )
        
        result = await self.db.execute(stmt)
        notification = result.scalar_one_or_none()
        
        if not notification:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Notification not found"
            )
        
        await self.db.delete(notification)
        await self.db.commit()
        
        return {
            "notification_id": notification_id,
            "message": "Notification deleted successfully"
        }

