import os
from time import time

from fastapi import APIRouter, UploadFile, File, HTTPException, Request

from app import mongo
from app.utils.response_util import response

router = APIRouter()

STATIC_FOLDER = "static"
PRODUCTS_FOLDER = os.path.join(STATIC_FOLDER, "images")
os.makedirs(PRODUCTS_FOLDER, exist_ok=True)


@router.post("/upload/{product_id}", tags=["Products"])
async def upload_product_image(
        request: Request,
        product_id: int,
        upload_file: UploadFile = File(...)
):
    start_time = time()

    product = await mongo.products_collection.find_one({"id": product_id})
    if not product:
        raise HTTPException(status_code=404, detail="Product not found")

    extension = os.path.splitext(upload_file.filename)[1] or ".jpg"
    filename = f"{product_id}{extension}"
    file_path = os.path.join(PRODUCTS_FOLDER, filename)

    with open(file_path, "wb") as file:
        file.write(await upload_file.read())

    image_url = f"{str(request.base_url).rstrip('/')}/api/v1/files/images/{filename}"
    return response({
        "imageUrl": image_url,
        "message": "Фото успешно загружено!",
        "ok": True
    }, start_time=start_time)
