"""
Routes API pour les cartes virtuelles
"""
from fastapi import APIRouter, Depends, HTTPException, Request, status, Query
from fastapi.responses import HTMLResponse
from sqlalchemy.orm import Session
from database import get_db
from models.models import CardVirtual, CardVirtualUser, User
from models_extra.virtual_card import VirtualCardPurchase, VirtualCardPurchaseStatus
from core.auth import get_current_user
from schemas.virtual_card import (
    VirtualCardCreate,VirtualCardRead,BuyCardRequest
)
from services.virtual_card_service import create_carte_virtual, get_all_card_virtual,buy_virtual_card
from typing import List, Optional
import logging
from pathlib import Path
from datetime import datetime

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

"""
Route supplémentaire à ajouter dans virtual_card_routes.py
"""

@router.post("/virtual_cards")
async def create_virtual_carte(validation_request:VirtualCardCreate,db: Session = Depends(get_db)):
    card = await create_carte_virtual(validation_request, db=db)
    return card

@router.get("/all/card_virtual", response_model = list[VirtualCardRead])
async def get_all_card(db: Session = Depends(get_db)):
    card_db = await get_all_card_virtual(db)
    return card_db

@router.post("/card_virtual/buy")
async def buy_virtual(data: BuyCardRequest,db: Session = Depends(get_db),current_user: User = Depends(get_current_user)):
    return await buy_virtual_card(data=data, db=db, current_user=current_user)

@router.get("/cards/me/all")
def get_my_cards(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):

    cards = (
        db.query(CardVirtualUser, CardVirtual)
        .join(CardVirtual, CardVirtual.id == CardVirtualUser.card_id)
        .filter(CardVirtualUser.user_id == current_user.id)
        .all()
    )

    return [
        {
            "id": card.id,
            "type": card.type_card,
            "price": card.price,
            "currency": card.currency,
            "acquired_at": cu.acquired_at,
            "card_user_id": cu.id,
        }
        for cu, card in cards
    ]
