from typing import List, Optional
from sqlalchemy.orm import Session
from app.models.device_token import DeviceToken
from app.schemas.device_token import DeviceTokenCreate
import logging

logger = logging.getLogger('adimsayar')

class DeviceTokenService:
    @staticmethod
    def get_user_device_tokens(db: Session, user_id: int) -> List[DeviceToken]:
        """사용자의 모든 활성화된 디바이스 토큰을 조회합니다."""
        tokens = db.query(DeviceToken).filter(
            DeviceToken.user_id == user_id,
            DeviceToken.is_active == True
        ).all()
        return tokens

    @staticmethod
    def add_device_token(db: Session, user_id: int, token: str, device_type: str) -> DeviceToken:
        """사용자의 디바이스 토큰을 등록하거나 업데이트합니다."""
        # 이미 존재하는 토큰인지 확인
        existing_token = db.query(DeviceToken).filter(
            DeviceToken.device_token == token
        ).first()
        
        if existing_token:
            # 같은 사용자의 토큰이면 활성화만 업데이트
            if existing_token.user_id == user_id:
                existing_token.is_active = True
                db.commit()
                db.refresh(existing_token)
                logger.info(f"디바이스 토큰 활성화 업데이트: {token[:10]}... (user_id: {user_id})")
                return existing_token
            
            # 다른 사용자의 토큰이면 기존 연결 해제 후 새 사용자에게 할당
            existing_token.user_id = user_id
            existing_token.device_type = device_type
            existing_token.is_active = True
            db.commit()
            db.refresh(existing_token)
            logger.info(f"디바이스 토큰 재할당: {token[:10]}... (이전 사용자에서 user_id: {user_id}로)")
            return existing_token
        
        # 새 토큰 등록
        device_token = DeviceToken(
            user_id=user_id,
            device_token=token,
            device_type=device_type,
            is_active=True
        )
        db.add(device_token)
        db.commit()
        db.refresh(device_token)
        logger.info(f"새 디바이스 토큰 등록: {token[:10]}... (user_id: {user_id})")
        return device_token

    @staticmethod
    def deactivate_device_token(db: Session, user_id: int, token: str) -> Optional[DeviceToken]:
        """사용자의 디바이스 토큰을 비활성화합니다."""
        device_token = db.query(DeviceToken).filter(
            DeviceToken.user_id == user_id,
            DeviceToken.device_token == token
        ).first()
        
        if not device_token:
            logger.warning(f"비활성화할 디바이스 토큰을 찾을 수 없음: {token[:10]}... (user_id: {user_id})")
            return None
        
        device_token.is_active = False
        db.commit()
        db.refresh(device_token)
        logger.info(f"디바이스 토큰 비활성화: {token[:10]}... (user_id: {user_id})")
        return device_token

    @staticmethod
    def get_all_active_tokens(db: Session) -> List[DeviceToken]:
        """모든 활성화된 디바이스 토큰을 조회합니다."""
        return db.query(DeviceToken).filter(DeviceToken.is_active == True).all() 