"""
Routes pour les transactions NFC avec cartes physiques
"""
from fastapi import APIRouter, Depends, HTTPException, Request
from sqlalchemy.orm import Session
from database import get_db
from services.nfc_transaction_service import NFCTransactionService
from models.models import User
from core.auth import get_current_user
from pydantic import BaseModel, Field
from typing import List, Dict, Any
import logging

logger = logging.getLogger(__name__)
router = APIRouter()

class NFCPaymentRequest(BaseModel):
    """Requête pour un paiement NFC"""
    card_uid: str = Field(..., description="UID de la carte NFC")
    amount: float = Field(..., description="Montant du paiement")
    device_info: str = Field(None, description="Informations de l'appareil")
    location: str = Field(None, description="Localisation")

class NFCRechargeRequest(BaseModel):
    """Requête pour une recharge NFC"""
    card_uid: str = Field(..., description="UID de la carte NFC")
    amount: float = Field(..., description="Montant de la recharge")
    device_info: str = Field(None, description="Informations de l'appareil")
    location: str = Field(None, description="Localisation")

@router.post("/nfc-transactions/payment", response_model=Dict[str, Any])
async def process_nfc_payment(
    request: NFCPaymentRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """Traiter un paiement NFC avec carte physique"""
    try:
        # Vérifier si le compte est bloqué
        from middleware.account_blocking import check_account_blocked
        check_account_blocked(current_user, allow_recharge=False)

        result = NFCTransactionService.process_nfc_payment(
            db=db,
            card_uid=request.card_uid,
            amount=request.amount,
            merchant_user_id=current_user.id,
            device_info=request.device_info,
            location=request.location
        )
        
        logger.info(f"Paiement NFC traité: {request.amount} FCFA avec carte {request.card_uid}")
        return result
        
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"Erreur paiement NFC: {str(e)}")
        raise HTTPException(status_code=500, detail="Erreur lors du paiement NFC")

@router.post("/nfc-transactions/recharge", response_model=Dict[str, Any])
async def process_nfc_recharge(
    request: NFCRechargeRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """Traiter une recharge NFC avec carte physique"""
    try:
        result = NFCTransactionService.process_nfc_recharge(
            db=db,
            card_uid=request.card_uid,
            amount=request.amount,
            recharger_user_id=current_user.id,
            device_info=request.device_info,
            location=request.location
        )
        
        logger.info(f"Recharge NFC traitée: {request.amount} FCFA avec carte {request.card_uid}")
        return result
        
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"Erreur recharge NFC: {str(e)}")
        raise HTTPException(status_code=500, detail="Erreur lors de la recharge NFC")

@router.get("/nfc-transactions/history", response_model=List[Dict[str, Any]])
async def get_nfc_transaction_history(
    limit: int = 50,
    offset: int = 0,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """Récupérer l'historique des transactions NFC de l'utilisateur"""
    try:
        history = NFCTransactionService.get_nfc_transaction_history(
            db=db,
            user_id=current_user.id,
            limit=limit,
            offset=offset
        )
        
        return history
        
    except Exception as e:
        logger.error(f"Erreur récupération historique NFC: {str(e)}")
        raise HTTPException(status_code=500, detail="Erreur lors de la récupération de l'historique")

@router.post("/nfc-transactions/validate-card")
async def validate_nfc_card(
    card_uid: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """Valider une carte NFC avant transaction"""
    try:
        from services.nfc_card_service import NFCCardService
        
        card = NFCCardService.get_card_by_uid(db, card_uid)
        if not card:
            raise HTTPException(status_code=404, detail="Carte NFC introuvable")
        
        if card.status != "active":
            raise HTTPException(status_code=400, detail="Carte NFC inactive")
        
        # Récupérer les informations du propriétaire
        owner = db.query(User).filter(User.id == card.user_id).first()
        
        return {
            "valid": True,
            "card_uid": card.card_uid,
            "card_number": card.card_number,
            "owner_name": owner.full_name if owner else "Inconnu",
            "owner_phone": owner.phone if owner else "Inconnu",
            "balance": card.balance,
            "max_balance": card.max_balance,
            "is_primary": card.is_primary
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Erreur validation carte NFC: {str(e)}")
        raise HTTPException(status_code=500, detail="Erreur lors de la validation de la carte")

@router.get("/nfc-transactions/stats", response_model=Dict[str, Any])
async def get_nfc_transaction_stats(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """Récupérer les statistiques des transactions NFC de l'utilisateur"""
    try:
        from models.models import Transaction, TransactionType
        from sqlalchemy import func
        
        # Statistiques des transactions NFC
        stats = db.query(
            Transaction.transaction_type,
            func.count(Transaction.id).label('count'),
            func.sum(Transaction.amount).label('total_amount')
        ).filter(
            Transaction.user_id == current_user.id,
            Transaction.transaction_type.in_([
                TransactionType.NFC_DEPOSIT,
                TransactionType.NFC_WITHDRAWAL,
                TransactionType.RECHARGE_BY_BUSINESS
            ])
        ).group_by(Transaction.transaction_type).all()
        
        # Formater les résultats
        result = {
            "total_transactions": sum(stat.count for stat in stats),
            "total_amount": sum(abs(stat.total_amount) for stat in stats),
            "by_type": {}
        }
        
        for stat in stats:
            result["by_type"][stat.transaction_type.value] = {
                "count": stat.count,
                "total_amount": abs(stat.total_amount) if stat.total_amount else 0
            }
        
        return result
        
    except Exception as e:
        logger.error(f"Erreur statistiques NFC: {str(e)}")
        raise HTTPException(status_code=500, detail="Erreur lors de la récupération des statistiques")
