import multer from "multer";
import path from "path";
import fs from "fs";
import { fileURLToPath } from "url";
import { env } from "../config/env.js";
import { ApiError } from "./asyncHandler.js";

// مجلد المرفقات ثابت داخل المشروع مهما كان دليل التشغيل (server/uploads)
const serverRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
export const uploadDir = path.resolve(serverRoot, env.uploadDir);
fs.mkdirSync(uploadDir, { recursive: true });

export const ALLOWED_EXTENSIONS = [".pdf", ".jpg", ".jpeg", ".png", ".webp"];
export const ALLOWED_MIME = new Set([
  "application/pdf",
  "image/jpeg",
  "image/jpg",
  "image/png",
  "image/webp",
]);
export const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB

// إصلاح مشكلة تشفير أسماء الملفات العربية (busboy/multer يفكها كـ latin1)
export function decodeFileName(name: string): string {
  let mojibake = false;
  for (const ch of name) {
    const c = ch.codePointAt(0)!;
    if (c >= 0x80 && c <= 0xff) {
      mojibake = true;
      break;
    }
  }
  if (!mojibake) return name;
  const decoded = Buffer.from(name, "latin1").toString("utf8");
  if (decoded.includes("\uFFFD")) return name;
  return decoded;
}

const storage = multer.diskStorage({
  destination: (_req, _file, cb) => cb(null, uploadDir),
  filename: (_req, file, cb) => {
    const safe = decodeFileName(file.originalname)
      .replace(/[^\w.\-\u0600-\u06FF]+/g, "_")
      .replace(/^\.+/, "")
      .slice(-80);
    cb(null, `${Date.now()}-${Math.random().toString(36).slice(2, 8)}-${safe}`);
  },
});

export const upload = multer({
  storage,
  limits: { fileSize: MAX_FILE_SIZE, files: 1 },
  fileFilter: (_req, file, cb) => {
    const ext = path.extname(decodeFileName(file.originalname)).toLowerCase();
    if (!ALLOWED_EXTENSIONS.includes(ext)) {
      return cb(new ApiError(400, "نوع الملف غير مدعوم. الصيغ المسموحة: PDF, JPG, JPEG, PNG, WEBP"));
    }
    const mime = file.mimetype.toLowerCase();
    if (!ALLOWED_MIME.has(mime)) {
      return cb(new ApiError(400, "نوع MIME للملف غير مسموح"));
    }
    return cb(null, true);
  },
});

export function resolveFilePath(storedName: string): string {
  // منع تجاوز المجلد (path traversal)
  const base = path.basename(storedName);
  return path.resolve(uploadDir, base);
}

export function deleteStoredFile(storedName: string) {
  try {
    fs.unlinkSync(resolveFilePath(storedName));
  } catch {
    // تجاهل أخطاء الحذف من القرص
  }
}