from utility.auth_token import get_current_user, get_current_admin
from models.models import KYCVerification, User, AdminUser
from services.kyc_users import upload_kyc_documents, get_kyc_status, validate_kyc, refuse_kyc
from fastapi import APIRouter, Depends, UploadFile, File, HTTPException
from sqlalchemy.orm import Session
from database import get_db 

router = APIRouter()

@router.post("/financials/user/profile/profile-kycs")
async def upload_kyc(
    current_user: User = Depends(get_current_user),
    front_image: UploadFile = File(...),
    back_image: UploadFile = File(...),
    db: Session = Depends(get_db),
):
    if not current_user:
        raise HTTPException(status_code=401, detail="Unauthorized")

    result = await upload_kyc_documents(
        user=current_user,
        front_image=front_image,
        back_image=back_image,
        db=db,
    )
    return result

@router.get("/financials/user/profile/profile-kycs/status")
async def kyc_status(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
):
    if not current_user:
        raise HTTPException(status_code=401, detail="Unauthorized")

    result = await get_kyc_status(user=current_user, db=db)
    return result

@router.patch("/financials/admin/kyc/validate/{kyc_id}")
async def validate_kyc_endpoint(
    kyc_id: str,
    current_user: AdminUser = Depends(get_current_admin),
    db: Session = Depends(get_db),
):
       # Vérification accès admin
    if not current_user or not current_user.is_admin:
        raise HTTPException(status_code=401, detail="Unauthorized")

    # Récupérer le KYC par ID + pending
    kyc_record = db.query(KYCVerification).filter(
        KYCVerification.id == kyc_id,
        KYCVerification.status == "pending"
    ).first()

    if not kyc_record:
        raise HTTPException(status_code=404, detail="KYC introuvable ou pas en attente.")

    result = await validate_kyc(kyc_id=kyc_id, db=db)
    return result

@router.patch("/financials/admin/kyc/refuse/{kyc_id}")
async def refuse_kyc_endpoint(
    kyc_id: str,
    current_user: AdminUser = Depends(get_current_admin),
    db: Session = Depends(get_db),
):
    # Vérification accès admin
    if not current_user or not current_user.is_admin:
        raise HTTPException(status_code=401, detail="Unauthorized")

    # Récupérer le KYC par ID + pending
    kyc_record = db.query(KYCVerification).filter(
        KYCVerification.id == kyc_id,
        KYCVerification.status == "pending"
    ).first()

    if not kyc_record:
        raise HTTPException(status_code=404, detail="KYC introuvable ou pas en attente.")

    # Appeler la fonction
    result = await refuse_kyc(kyc_record=kyc_record, db=db)
    return result
