from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import Dict, Any, Optional
from pydantic import BaseModel
import logging

from app.schemas.notification import PushNotificationRequest
from app.api import deps
from app.services.push_notification_service import PushNotificationService
from app.services.expo_push_notification_service import ExpoPushNotificationService
from app.core.config import settings

logger = logging.getLogger("adimsayar")

router = APIRouter()

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

class SendPushToUserRequest(SendPushNotificationRequest):
    user_id: int

@router.post("/test-send")
def test_send_push_notification(
    req: SendPushNotificationRequest,
    db: Session = Depends(deps.get_db),
    current_user = Depends(deps.get_current_user)
):
    """
    테스트 용도로 현재 로그인한 사용자에게 푸시 알림을 보냅니다.
    """
    # 관리자 권한 확인 (필요 시 주석 해제)
    # if not current_user.is_admin:
    #     raise HTTPException(
    #         status_code=status.HTTP_403_FORBIDDEN,
    #         detail="Only admin users can send test notifications"
    #     )
    
    success = PushNotificationService.send_push_to_user(
        db=db,
        user_id=current_user.id,
        title=req.title,
        message=req.message,
        data=req.data,
        notification_type=req.notification_type
    )
    
    if not success:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to send push notification"
        )
    
    return {"status": "success", "message": "Push notification sent successfully"}

@router.post("/admin/send-to-user")
def admin_send_push_to_user(
    req: SendPushToUserRequest,
    db: Session = Depends(deps.get_db),
    current_user = Depends(deps.get_current_user)
):
    """
    관리자가 특정 사용자에게 푸시 알림을 보냅니다.
    """
    # 관리자 권한 확인
    if not current_user.is_admin:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only admin users can send notifications to specific users"
        )
    
    success = PushNotificationService.send_push_to_user(
        db=db,
        user_id=req.user_id,
        title=req.title,
        message=req.message,
        data=req.data,
        notification_type=req.notification_type
    )
    
    if not success:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to send push notification"
        )
    
    return {"status": "success", "message": f"Push notification sent to user ID {req.user_id}"}

@router.post("/expo-test-send")
def test_send_expo_push(
    req: PushNotificationRequest,
    db: Session = Depends(deps.get_db),
    current_user = Depends(deps.get_current_user),
):
    """
    현재 로그인한 사용자에게 Expo 푸시 알림을 보내는 테스트 엔드포인트.
    """
    try:
        success = ExpoPushNotificationService.send_push_to_user(
            db=db,
            user_id=current_user.id,
            title=req.title,
            message=req.message,
            data=req.data,
            notification_type=req.notification_type or "test"
        )
        
        if success:
            return {"status": "success", "message": "Expo push notification sent successfully"}
        else:
            raise HTTPException(status_code=500, detail="Failed to send Expo push notification")
    
    except Exception as e:
        logger.error(f"Error sending Expo push notification: {str(e)}")
        raise HTTPException(status_code=500, detail="Failed to send Expo push notification") 