# app/api/v1/endpoints/notifications.py
from fastapi import APIRouter, Depends, HTTPException, status
from typing import List, Dict, Any, Optional
from sqlalchemy.orm import Session
from pydantic import BaseModel
from app.api import deps
from app.schemas.notification import NotificationResponse
from app.services.notification_service import NotificationService
import logging
from sqlalchemy import text

router = APIRouter()

logger = logging.getLogger(__name__)

class MarkNotificationReadRequest(BaseModel):
    notification_id: int

class DeleteNotificationRequest(BaseModel):
    notification_id: int

class SoftDeleteNotificationRequest(BaseModel):
    notification_id: int

class SendFirebaseNotificationRequest(BaseModel):
    title: str
    message: str
    notification_type: str = "general"
    data: Optional[Dict[str, Any]] = None

@router.get("/", response_model=List[NotificationResponse])
def get_user_notifications(
    db: Session = Depends(deps.get_db),
    current_user = Depends(deps.get_current_user)
):
    """
    Retrieve notifications for the logged-in user.
    """
    notifications = NotificationService.get_notifications(db, current_user.id)
    
    # Instead of raising a 404 when there are no notifications,
    # you can simply return an empty list.
    if notifications is None:
        return []
    return notifications

@router.post("/mark-read", response_model=NotificationResponse)
def mark_notification_read(
    req: MarkNotificationReadRequest,
    db: Session = Depends(deps.get_db),
    current_user = Depends(deps.get_current_user)
):
    """
    Update the read_at field of a given notification using the notification_id 
    provided in the body of a POST request.
    """
    updated_notification = NotificationService.mark_notification_as_read(
        db, req.notification_id, current_user.id
    )
    if updated_notification is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Notification not found or not authorized"
        )
    return NotificationResponse.from_orm(updated_notification)

@router.post("/soft-delete", response_model=NotificationResponse)
def soft_delete_notification(
    req: SoftDeleteNotificationRequest,
    db: Session = Depends(deps.get_db),
    current_user = Depends(deps.get_current_user)
):
    """
    알림을 소프트 삭제합니다 (실제 삭제하지 않고 data 필드에 삭제 정보 추가)
    """
    try:
        # 소프트 삭제 실행
        deleted_notification = NotificationService.soft_delete_notification(
            db, req.notification_id, current_user.id
        )
        
        if deleted_notification is None:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Notification not found or not authorized"
            )
        
        # 명시적으로 다시 조회하여 변경 확인
        verify_result = db.execute(
            text("SELECT data FROM notifications WHERE id = :id"),
            {"id": req.notification_id}
        ).fetchone()
        
        logger.info(f"Verification query - Data field: {verify_result[0] if verify_result else None}")
        
        # JSON 직렬화 오류 방지를 위해 명시적으로 모델을 변환
        return NotificationResponse.from_orm(deleted_notification)
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error in soft delete endpoint: {str(e)}", exc_info=True)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Internal server error: {str(e)}"
        )

@router.post("/send-firebase", response_model=NotificationResponse)
def send_firebase_notification(
    req: SendFirebaseNotificationRequest,
    db: Session = Depends(deps.get_db),
    current_user = Depends(deps.get_current_user)
):
    """
    Firebase Cloud Messaging을 통해 현재 로그인한 사용자에게 푸시 알림을 전송합니다.
    """
    try:
        notification = NotificationService.send_firebase_notification(
            db=db,
            user_id=current_user.id,
            title=req.title,
            message=req.message,
            notif_type=req.notification_type,
            data=req.data
        )
        return NotificationResponse.from_orm(notification)
    except Exception as e:
        logger.error(f"Error sending Firebase notification: {str(e)}", exc_info=True)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Error sending Firebase notification: {str(e)}"
        )