# app/api/v1/endpoints/device_tokens.py
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List
from pydantic import BaseModel

from app.api import deps
from app.schemas.device_token import DeviceTokenCreate, DeviceTokenResponse
from app.services.device_token_service import DeviceTokenService

router = APIRouter()

class RegisterDeviceTokenRequest(BaseModel):
    device_token: str
    device_type: str  # "ios", "android", "web"

class DeactivateDeviceTokenRequest(BaseModel):
    device_token: str

@router.post("/register", response_model=DeviceTokenResponse)
def register_device_token(
    req: RegisterDeviceTokenRequest,
    db: Session = Depends(deps.get_db),
    current_user = Depends(deps.get_current_user)
):
    """
    사용자 디바이스 토큰을 등록합니다. 
    이미 등록된 토큰이라면 활성 상태로 업데이트합니다.
    """
    device_token = DeviceTokenService.add_device_token(
        db=db,
        user_id=current_user.id,
        device_token=req.device_token,
        device_type=req.device_type
    )
    return DeviceTokenResponse.from_orm(device_token)

@router.post("/deactivate", response_model=DeviceTokenResponse)
def deactivate_device_token(
    req: DeactivateDeviceTokenRequest,
    db: Session = Depends(deps.get_db),
    current_user = Depends(deps.get_current_user)
):
    """
    사용자 디바이스 토큰을 비활성화합니다.
    로그아웃 시 호출해야 합니다.
    """
    device_token = DeviceTokenService.deactivate_device_token(
        db=db,
        user_id=current_user.id,
        device_token=req.device_token
    )
    
    if not device_token:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Device token not found or already deactivated"
        )
    
    return DeviceTokenResponse.from_orm(device_token)

@router.get("/", response_model=List[DeviceTokenResponse])
def get_user_device_tokens(
    db: Session = Depends(deps.get_db),
    current_user = Depends(deps.get_current_user)
):
    """
    사용자의 모든 디바이스 토큰을 조회합니다.
    """
    tokens = DeviceTokenService.get_user_device_tokens(db, current_user.id)
    return [DeviceTokenResponse.from_orm(token) for token in tokens] 