import json
from typing import Optional
import uuid
from fastapi import APIRouter, Depends, FastAPI, HTTPException
from pydantic import BaseModel
from requests import Session
from core.task import generate_transaction_id
from database import get_db
from models.models import Transaction, TransactionStatus, TransactionType, User
from utility.auth_token import get_current_user
from utility.transfert import CinetPayServiceTransfert
from core.config import settings
from services.users import get_user_wallet

router = APIRouter()

# CONFIG CINETPAY
APIKEY = "VOTRE_API_KEY"
API_PASSWORD = "VOTRE_MDP_API"

cinetpay = CinetPayServiceTransfert()

# ------------ MODELE DE DEMANDE -------------- #

class TransferRequest(BaseModel):
    amount: int
    phone: str
    payment_method: Optional[str] = ""

# ------------ ROUTE POUR ENVOYER L'ARGENT -------------- #

@router.post("/financials/send-money")
async def send_money(data: TransferRequest, current_user: User = Depends(get_current_user), db: Session = Depends(get_db)):

    user_wallet = get_user_wallet(current_user.id, db=db)

    if not user_wallet:
        raise HTTPException(404, "Wallet introuvable")

    if user_wallet.balance < data.amount:
        raise HTTPException(400, detail= "Solde insuffisant pour effectuer ce retrait")
    
    user_wallet.balance -= data.amount
    db.commit()
    db.refresh(user_wallet)

    transaction_id = generate_transaction_id("RETR") 
    
    client_txn = Transaction(
            id=str(uuid.uuid4()),
            user_id=current_user.id,
            transaction_type=TransactionType.RETRAIT,
            amount=-data.amount,
            status=TransactionStatus.PENDING,
            description=f"Retrait d'argent vers {data.phone}",
            reference=  transaction_id,
        )

    db.add(client_txn)
    db.commit()
    db.refresh(client_txn)
    print("Transaction de retrait créée avec ID:", data.payment_method)
    if data.payment_method == "WAVECI":
        payload = {
            "data": json.dumps([
                {
                    "amount": str(data.amount),
                    "phone": data.phone,
                    "prefix": f"225",
                    "notify_url": settings.CINETPAY_NOTIFY_URL,
                    "client_transaction_id": transaction_id ,
                    "payment_method":"WAVECI"
                }
            ])
        }
    else:
        payload = {
            "data": json.dumps([
                {
                    "amount": str(data.amount),
                    "phone": data.phone,
                    "prefix": f"225",
                    "notify_url": settings.CINETPAY_NOTIFY_URL,
                    "client_transaction_id": transaction_id ,
                    "payment_method":""
                }
            ])
        }

    result =  await cinetpay.send_transfer(
       transfer_data= payload, transaction_id= transaction_id
    )
    
    # Si échec API -> remboursement
    if result.get("code") != 0:
        user_wallet.balance += data.amount
        db.commit()
        raise HTTPException(500, f"Erreur CinetPay: {result}")
    return result

