from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import Dict, Any, Optional, List
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
from app.services.notification_service import NotificationService
from app.services.device_token_service import DeviceTokenService
from app.core.firebase_config import send_firebase_multicast, initialize_firebase

logger = logging.getLogger("adimsayar")

router = APIRouter()

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

class TestPushRequest(BaseModel):
    title: str = "테스트 알림"
    message: str = "이것은 테스트 알림입니다."
    notification_type: str = "test"
    data: Optional[Dict[str, Any]] = None

@router.post("/send")
async def send_push_notification(
    req: SendPushNotificationRequest,
    db: Session = Depends(deps.get_db),
    current_user = Depends(deps.get_current_user)
):
    """
    현재 사용자에게 푸시 알림을 전송합니다.
    """
    try:
        result = await 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
        )
        
        return {"success": result, "message": "Push notification sent"}
    except Exception as e:
        logger.error(f"Error sending push notification: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Error sending push notification: {str(e)}"
        )

@router.post("/test")
async def test_push_notification(
    req: TestPushRequest = None,
    db: Session = Depends(deps.get_db),
    current_user = Depends(deps.get_current_user)
):
    """
    Firebase 및 Expo 푸시 알림 테스트 엔드포인트
    """
    try:
        if req is None:
            req = TestPushRequest()
            
        # 알림 생성
        title = req.title
        message = req.message
        notification_type = req.notification_type
        data = req.data or {"test": "true", "type": "test"}
        
        # 알림 저장
        notification = NotificationService.create_notification(
            db=db, 
            user_id=current_user.id,
            notif_type=notification_type,
            title=title,
            message=message,
            data=data
        )
        db.commit()
        db.refresh(notification)
        
        # 푸시 알림 전송
        success = await PushNotificationService.send_push_to_user(
            db=db,
            user_id=current_user.id,
            title=title,
            message=message,
            data=data,
            notification_type=notification_type,
            save_to_db=False  # 이미 알림을 저장했으므로 중복 저장 방지
        )
        
        return {
            "success": success,
            "message": "Test push notification sent",
            "notification_id": notification.id
        }
    except Exception as e:
        logger.error(f"Error sending test push notification: {str(e)}", exc_info=True)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Error sending test push notification: {str(e)}"
        ) 