"""
Service de gestion des cartes virtuelles
"""
from services.users import get_user_wallet
from models.models import CardVirtual, CardVirtualUser, Notification, NotificationPriority, Transaction, TransactionStatus, TransactionType, User
from core.excption import HTTPException
from sqlalchemy.orm import Session
# from models import Card, VirtualCard
from models_extra.virtual_card import (
    VirtualCardPurchase, VirtualCardPrice, VirtualCardColor,
    VirtualCardPurchaseStatus
)
from schemas.virtual_card import VirtualCardCreate, VirtualCardRead,BuyCardRequest
from services.cinetpay_service import CinetPayService
from datetime import datetime
from fastapi import status
import uuid
import logging

logger = logging.getLogger(__name__)


async def create_carte_virtual(request_data: VirtualCardCreate, db: Session):
    new_card = CardVirtual(
        type_card=request_data.card_type,
        price=request_data.price,
        currency=request_data.currency
    )
    db.add(new_card)
    db.commit()
    db.refresh(new_card)
    return new_card

async def get_all_card_virtual(db: Session):
    cart_virtual = db.query(CardVirtual).all()
    return cart_virtual


async def buy_virtual_card(data: BuyCardRequest, db: Session, current_user: User):

    # Vérifier la carte
    card = db.query(CardVirtual).filter(CardVirtual.id == data.card_id).first()
    if not card:
        raise HTTPException(404, "Carte virtuelle introuvable")
    
    user = current_user
    
    # existing = db.query(CardVirtualUser).filter(
    #     CardVirtualUser.user_id == current_user.id,
    #     CardVirtualUser.card_id == card.id
    # ).first()
    # if existing:
    #     raise HTTPException(400, "Carte déjà achetée")

    # Vérifier le solde
    sender_wallet = get_user_wallet(user_id=user.id, db=db)
    if sender_wallet.balance < card.price:
        raise HTTPException(status_code= status.HTTP_400_BAD_REQUEST, detail ="Solde insuffisant")

    # Débiter l'utilisateur
    sender_wallet.balance -= card.price
    db.add(sender_wallet)

    #ASSOCIER LA CARTE AU USER
    card_user = CardVirtualUser(
        user_id=user.id,
        card_id=card.id
    )
    db.add(card_user)

    # Créer la transaction
    sender_txn = Transaction(
        id=str(uuid.uuid4()),
        user_id=user.id,
        transaction_type=TransactionType.PAIEMENT,
        amount=-card.price,
        status=TransactionStatus.COMPLETED,
        description=f"Achat de carte virtuelle {card.type_card}",
        reference=f"TRF-OUT-{uuid.uuid4().hex[:8]}",
        external_reference=str(uuid.uuid4())
    )
    db.add(sender_txn)

    # Notification
    notification = Notification(
        id=str(uuid.uuid4()),
        user_id=user.id,
        title="Achat de carte virtuelle",
        message=f"Vous avez acheté la carte virtuelle {card.type_card} pour {card.price} XOF.",
        type="wallet_debit",
        priority=NotificationPriority.MEDIUM,
        amount=card.price,
        created_at=datetime.utcnow()
    )
    db.add(notification)

    # Enregistrer
    db.commit()

    db.refresh(sender_wallet)
    db.refresh(sender_txn)
    db.refresh(notification)

    return {
        "message": "Carte virtuelle achetée avec succès",
        "status": status.HTTP_200_OK,
        "card": {
            "id": card.id,
            "type": card.type_card,
            "price": card.price,
            "currency": card.currency
        },
        "new_balance": sender_wallet.balance
    }
