"""
Routes API pour la gestion des cartes physiques NFC
"""
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from database import get_db
from services.card_service import CardService
from schemas.card import (
    CardCreate, CardUpdate, CardResponse, CardRechargeRequest, 
    CardRechargeResponse, CardBlockRequest, CardSearchRequest, CardListResponse
)
from core.auth import get_current_user
from models.models import User
from typing import List

router = APIRouter()

@router.post("/financials/add/cards")
async def create_card(
    card_data: CardCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """Créer une nouvelle carte physique"""
    try:
        card = CardService.create_card(db, current_user.id,card_data.phone)
        
        # Récupérer les infos utilisateur
        user = db.query(User).filter(User.id == card.user_id).first()
        card.user_phone = user.phone if user else None
        card.user_name = user.full_name if user else None
        
        return card
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

@router.get("/financials/cards/my-cards")
async def get_my_cards(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """Récupérer les cartes de l'utilisateur connecté"""
    cards = CardService.get_user_cards(db, current_user.id)
    
    # Ajouter les infos utilisateur
    for card in cards:
        user = db.query(User).filter(User.id == card.user_id).first()
        card.user_phone = user.phone if user else None
        card.user_name = user.full_name if user else None
    
    return cards

@router.get("/cards/{card_id}", response_model=CardResponse)
async def get_card(
    card_id: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """Récupérer une carte par son ID"""
    card = CardService.get_card_by_id(db, card_id)
    if not card:
        raise HTTPException(status_code=404, detail="Carte non trouvée")
    
    # Vérifier que l'utilisateur peut accéder à cette carte
    if card.user_id != current_user.id and current_user.tim_account_type != "ADMIN":
        raise HTTPException(status_code=403, detail="Accès non autorisé")
    
    # Ajouter les infos utilisateur
    user = db.query(User).filter(User.id == card.user_id).first()
    card.user_phone = user.phone if user else None
    card.user_name = user.full_name if user else None
    
    return card

@router.put("/cards/{card_id}/status", response_model=CardResponse)
async def update_card_status(
    card_id: str,
    card_update: CardUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """Mettre à jour le statut d'une carte"""
    card = CardService.get_card_by_id(db, card_id)
    if not card:
        raise HTTPException(status_code=404, detail="Carte non trouvée")
    
    # Vérifier les permissions
    if card.user_id != current_user.id and current_user.tim_account_type != "ADMIN":
        raise HTTPException(status_code=403, detail="Accès non autorisé")
    
    try:
        updated_card = CardService.update_card_status(
            db, card_id, card_update.status, card_update.reason
        )
        
        # Ajouter les infos utilisateur
        user = db.query(User).filter(User.id == updated_card.user_id).first()
        updated_card.user_phone = user.phone if user else None
        updated_card.user_name = user.full_name if user else None
        
        return updated_card
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

@router.post("/cards/{card_id}/block", response_model=CardResponse)
async def block_card(
    card_id: str,
    block_request: CardBlockRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """Bloquer une carte (perte/vol)"""
    card = CardService.get_card_by_id(db, card_id)
    if not card:
        raise HTTPException(status_code=404, detail="Carte non trouvée")
    
    # Vérifier les permissions
    if card.user_id != current_user.id and current_user.tim_account_type != "ADMIN":
        raise HTTPException(status_code=403, detail="Accès non autorisé")
    
    # Déterminer le statut selon la raison
    if block_request.is_stolen:
        status = "stolen"
    elif block_request.is_lost:
        status = "lost"
    else:
        status = "blocked"
    
    try:
        blocked_card = CardService.update_card_status(
            db, card_id, status, block_request.reason
        )
        
        # Ajouter les infos utilisateur
        user = db.query(User).filter(User.id == blocked_card.user_id).first()
        blocked_card.user_phone = user.phone if user else None
        blocked_card.user_name = user.full_name if user else None
        
        return blocked_card
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

@router.post("/cards/{card_id}/unblock", response_model=CardResponse)
async def unblock_card(
    card_id: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """Débloquer une carte (admin seulement)"""
    if current_user.tim_account_type != "ADMIN":
        raise HTTPException(status_code=403, detail="Seuls les administrateurs peuvent débloquer les cartes")
    
    try:
        unblocked_card = CardService.unblock_card(db, card_id)
        
        # Ajouter les infos utilisateur
        user = db.query(User).filter(User.id == unblocked_card.user_id).first()
        unblocked_card.user_phone = user.phone if user else None
        unblocked_card.user_name = user.full_name if user else None
        
        return unblocked_card
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

@router.post("/cards/recharge", response_model=CardRechargeResponse)
async def recharge_card(
    recharge_request: CardRechargeRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """Recharger une carte via le numéro de téléphone (Tim Business seulement)"""
    if current_user.tim_account_type != "TIM_BUSINESS":
        raise HTTPException(status_code=403, detail="Seuls les utilisateurs Tim Business peuvent recharger les cartes")
    
    try:
        result = CardService.recharge_card_by_phone(
            db, 
            recharge_request.phone, 
            recharge_request.amount, 
            current_user.id
        )
        return result
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

# Routes admin
@router.get("/admin/cards", response_model=CardListResponse)
async def get_all_cards_admin(
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=1000),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """Récupérer toutes les cartes (admin seulement)"""
    if current_user.tim_account_type != "ADMIN":
        raise HTTPException(status_code=403, detail="Accès non autorisé")
    
    cards = CardService.get_all_cards(db, skip, limit)
    
    # Ajouter les infos utilisateur
    for card in cards:
        user = db.query(User).filter(User.id == card.user_id).first()
        card.user_phone = user.phone if user else None
        card.user_name = user.full_name if user else None
    
    total = db.query(Card).count()
    
    return CardListResponse(
        cards=cards,
        total=total,
        page=skip // limit + 1,
        limit=limit
    )

@router.get("/admin/cards/search", response_model=List[CardResponse])
async def search_cards_admin(
    query: str = Query(..., description="Terme de recherche"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """Rechercher des cartes (admin seulement)"""
    if current_user.tim_account_type != "ADMIN":
        raise HTTPException(status_code=403, detail="Accès non autorisé")
    
    cards = CardService.search_cards(db, query)
    
    # Ajouter les infos utilisateur
    for card in cards:
        user = db.query(User).filter(User.id == card.user_id).first()
        card.user_phone = user.phone if user else None
        card.user_name = user.full_name if user else None
    
    return cards
