
from fastapi import UploadFile, File, HTTPException
from sqlalchemy.orm import Session
from fastapi.responses import JSONResponse
import os
import uuid
from pathlib import Path
from core.excption import HTTPException, NotFoundException

from utility.users import show_user_by_id

MAX_FILE_SIZE = 2 * 1024 * 1024  # 2 Mo

UPLOAD_DIR = Path("uploads")
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)

async def upload_profile(id: int, db: Session, file: UploadFile = File(...)):
    if not file.content_type.startswith("image/"):
        raise HTTPException(status_code=400, detail="Le fichier doit être une image.")
    content = await file.read()
    
    if len(content) > MAX_FILE_SIZE:
        raise HTTPException(status_code=413, detail="La taille maximale autorisée est de 2 Mo.")
    extension = file.filename.split(".")[-1]
    unique_filename = f"{uuid.uuid4()}.{extension}"
    file_path = UPLOAD_DIR / unique_filename

    # Écrit le fichier
    with open(file_path, "wb") as buffer:
        buffer.write(content)

    # Retourne l'URL du fichier uploadé
    photo_url = f"http://localhost:8000/uploads/{unique_filename}"
    
    try:
        user_in_db = await show_user_by_id(id, db)
        if user_in_db:
            user_in_db.profil_photo_url = photo_url
            db.add(user_in_db)
            db.commit() 
            db.refresh(user_in_db) 
        else:
            
            raise NotFoundException(detail=f"Utilisateur avec ID {id} non trouvé.")

    except Exception as e:
        db.rollback() 
        raise HTTPException(status_code=500, detail=f"Erreur lors de la mise à jour de l'URL de la photo de profil : {e}")


    return JSONResponse({
        "message": "Photo de profil uploadée avec succès.",
        "photo_url": photo_url
    })
