from fastapi import APIRouter, Request, Depends
from fastapi.responses import JSONResponse
from utils.auth_helper import requires_permission, assert_actor_match
from utils.turnstile_helper import verify_turnstile
from utils.upload_helper import (
    response_error,
    response_success,
    store_uploaded_file_content,
)

router = APIRouter()

@router.options("/upload")
async def upload_options():
    return JSONResponse(content="OK", status_code=204)


@router.post("/upload", dependencies=[Depends(verify_turnstile)])
async def handle_request(
    request: Request,
    current_user=Depends(requires_permission("product_management"))
):
    assert_actor_match(current_user, request.headers.get("x-actor-id"))

    form_data = await request.form()
    action = str(form_data.get("action", "")).lower()
    req_type = str(form_data.get("type", "")).lower()
    file_name = str(form_data.get("fileName", "")).strip()

    if action == "deletefile":
        if not file_name or req_type not in ["img", "file_excel"]:
            return response_error("Thông tin xóa không hợp lệ.")

        sub_dir = "upload_img" if req_type == "img" else "upload_file_excel"
        from utils.upload_helper import UPLOADS_DIR
        import os

        file_path = os.path.join(UPLOADS_DIR, sub_dir, file_name)
        if os.path.isfile(file_path):
            try:
                os.remove(file_path)
                return response_success({"deleted": True, "file": file_name})
            except Exception:
                return response_error("Không thể xoá file.")
        return response_error("File không tồn tại.")

    if req_type not in ["img", "file_excel"]:
        return response_error("Thiếu hoặc sai loại file (type).")

    is_img = req_type == "img"
    sub_dir = "upload_img" if is_img else "upload_file_excel"

    if is_img:
        files = form_data.getlist("files")
        if not files:
            return response_error("Không tìm thấy file ảnh.")

        saved = []
        for file_obj in files:
            if not file_obj.filename:
                continue

            content = await file_obj.read()
            saved_info = store_uploaded_file_content(
                file_obj.filename,
                content,
                sub_dir=sub_dir,
                is_img=True,
            )
            saved.append(saved_info)

        return response_success([s["path"] for s in saved])

    file_obj = form_data.get("file")
    if not file_obj or not file_obj.filename:
        return response_error("Không tìm thấy file excel.")

    content = await file_obj.read()
    saved_info = store_uploaded_file_content(
        file_obj.filename,
        content,
        sub_dir=sub_dir,
        is_img=False,
    )
    return response_success([saved_info["path"]])