import crypto from "node:crypto";
import fs from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";

import { ApiError } from "../utils/ApiError.js";

const currentDir = path.dirname(fileURLToPath(import.meta.url));
const uploadsRoot = path.resolve(currentDir, "../../uploads/mgx");

const allowedMimeTypes = new Set([
  "application/pdf",
  "image/jpeg",
  "image/png",
  "image/webp",
]);

export const mgxUploadsController = {
  async uploadFile(req, res) {
    if (!req.file) {
      throw new ApiError(400, "Fichier requis.");
    }

    if (!allowedMimeTypes.has(req.file.mimetype)) {
      throw new ApiError(400, "Type de fichier non autorisé. Utilisez PDF, JPG, PNG ou WEBP.");
    }

    await fs.mkdir(uploadsRoot, { recursive: true });
    const extension = path.extname(req.file.originalname || "").toLowerCase() || ".bin";
    const filename = `${crypto.randomUUID()}${extension}`;
    const absolutePath = path.join(uploadsRoot, filename);

    await fs.writeFile(absolutePath, req.file.buffer);

    res.status(201).json({
      file_url: `/uploads/mgx/${filename}`,
      filename,
      original_name: req.file.originalname,
      size: req.file.size,
      mime_type: req.file.mimetype,
    });
  },
};
