from fastapi import APIRouter, UploadFile, File, Form, HTTPException
from pathlib import Path
import shutil

from api.config import DATA_ROOT
from api.utils.storage import get_company_document_path


router = APIRouter(prefix="/documents", tags=["Documents"])


@router.post("/upload")
def upload_document(
    company_name: str = Form(...),
    document_type: str = Form(...),
    file: UploadFile = File(...)
):
    if not file.filename:
        raise HTTPException(status_code=400, detail="Ficheiro inválido")

    target_dir = get_company_document_path(
        DATA_ROOT,
        company_name,
        document_type
    )

    file_path = target_dir / file.filename

    with open(file_path, "wb") as buffer:
        shutil.copyfileobj(file.file, buffer)

    return {
        "message": "Documento carregado com sucesso",
        "company": company_name,
        "document_type": document_type,
        "stored_path": str(file_path)
    }
