from typing import List
import uuid
from services.users import get_user_wallet
from utility.stock import get_admin_stock
from sqlalchemy.orm import Session, joinedload
from fastapi import APIRouter, Depends, File, Form, Request, UploadFile, HTTPException
from sqlalchemy.orm import Session
from sqlalchemy.exc import SQLAlchemyError, IntegrityError
from schemas.loans import CommissionRequest, LoanSchema, RepayLoanRequest, RepayLoanResponseSchema
from database import get_db
from utility.auth_token import get_current_user
from models.models import Loan, LoanStatus, Notification, NotificationPriority, Transaction, TransactionStatus, TransactionType, User
from services.loans import create_loan_with_info, loands_rembousement_users, repay_loan,create_commission_users

import logging

logger = logging.getLogger(__name__)

router = APIRouter()

@router.post("/financials/loan/transaction")
async def create_loan(
    request: Request,
    currence_amount: CommissionRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    body_data = {
        "client_host": request.client.host,
        "user_id": current_user.id
    }

    logger.info(f"Loan transaction request received: {body_data}")

    
        # On appelle ton service
    result = await create_loan_with_info(
            current_user=current_user.id,
            db=db,
            request_amount=currence_amount
        )
    return result
@router.get("/financials/users/walletborrowers")
def get_my_loans(
    db: Session = Depends(get_db), 
    current_user: User = Depends(get_current_user)   # 👈 user connecté
):
    loans = db.query(Loan).filter(Loan.user_id == current_user.id).all()
    return loans

@router.post("/financials/users/walletborrowers")
async def loans_remboursement(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    loans_rembour =  await repay_loan(db=db, current_user=current_user)
    return loans_rembour

@router.post("/financials/users/commissions")
async def loans_remboursement(
    request: CommissionRequest,
    user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    loans_commission =  await create_commission_users(request=request, db=db, current_user=user.id)
    return loans_commission


@router.post("/financials/users/rembousement/web")
async def loans_remboursement(
    request: CommissionRequest,
    user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    loans_commission =  await loands_rembousement_users(request=request, db=db, current_user=user.id)
    return loans_commission


@router.post("/admin/loans/{loan_id}/approve", response_model=dict)
def approve_loan(loan_id: str, db: Session = Depends(get_db)):
    # 1️⃣ Récupérer le prêt
    loan = db.query(Loan).filter(Loan.id == loan_id).first()
    if not loan:
        raise HTTPException(status_code=404, detail="Prêt introuvable")
    if loan.status != LoanStatus.PENDING:
        raise HTTPException(status_code=400, detail="Ce prêt n'est pas en attente")

    # 2️⃣ Récupérer l'utilisateur et son wallet
    user = db.query(User).filter(User.id == loan.user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="Utilisateur introuvable")

    wallet = get_user_wallet(user.id, db)
    # 3️⃣ Vérifier stock admin
    admin_stock = get_admin_stock(db)
    if admin_stock.balance < loan.amount:
        raise HTTPException(status_code=400, detail="Fonds insuffisants dans le stock admin")

    # 4️⃣ Débiter le stock admin et créditer le portefeuille utilisateur
    admin_stock.balance -= loan.amount
    admin_stock.total_debits += loan.amount
    wallet.balance += loan.amount

    # 5️⃣ Créer la transaction
    transaction = Transaction(
        id=str(uuid.uuid4()),
        user_id=user.id,
        transaction_type=TransactionType.PRET_MOBILE,
        amount=loan.amount,
        commission_amount=loan.amount * loan.interest_rate,
        commission_rate=loan.interest_rate,
        status=TransactionStatus.COMPLETED,
        description=f"Approbation du prêt {loan.id[:8]}",
        reference=f"LOAN-{loan.id[:8]}",
        external_reference=loan.id
    )
    db.add(transaction)

    # 6️⃣ Mettre à jour le statut du prêt
    loan.status = LoanStatus.APPROVED

    # 7️⃣ Créer une notification pour informer l'utilisateur
    notification = Notification(
        id=str(uuid.uuid4()),
        user_id=user.id,
        title="Votre prêt a été approuvé 🎉",
        message=f"Votre demande de prêt d’un montant de {loan.amount:.0f} FCFA a été approuvée et créditée sur votre compte.",
        type="LOAN_APPROVED",
        priority=NotificationPriority.HIGH,
        is_read=False,
        amount=loan.amount,
        merchant="TIMCASH",
        action_url=f"/loans/{loan.id}"
    )
    db.add(notification)

    # 8️⃣ Valider toutes les opérations
    db.commit()

    return {
        "message": "Prêt approuvé avec succès",
        "loan_id": loan.id,
        "status": loan.status,
        "notification": {
            "title": notification.title,
            "message": notification.message,
            "type": notification.type
        }
    }
@router.get("/loans/all")
def get_all_loans(db: Session = Depends(get_db)):
    """
    Retourne la liste de tous les prêts avec :
    - les informations détaillées du prêt
    - les informations de l'utilisateur associé
    - les fichiers recto et verso de la pièce d'identité
    """
    
    loans = (
        db.query(Loan)
        .options(joinedload(Loan.user))
        .order_by(Loan.created_at.desc())
        .all()
    )

    if not loans:
        raise HTTPException(status_code=404, detail="Aucun prêt trouvé")

    results = []

    for loan in loans:
        user = loan.user

        results.append({
            # --- Infos sur le prêt ---
            "loan_id": loan.id,
            "amount": loan.amount,
            "interest_rate": loan.interest_rate,
            "remaining_balance": loan.remaining_balance,
            "status": loan.status,
            "due_date": loan.due_date,
            "created_at": loan.created_at,

            # --- Infos sur l'utilisateur ---
            "user": {
                "id": user.id if user else None,
                "full_name": user.full_name if user and user.full_name else "Utilisateur inconnu",
                "email": user.email if user else None,
                "phone": user.phone if user and user.phone else None,
                "account_type": user.tim_account_type.value if user else None,
                "genre": user.genre if user else None,
                "country": getattr(user, "country", None),
                "city": getattr(user, "city", None),
                "created_at": user.created_at if user else None,
            }
        })

    return results