import "server-only";
import { randomUUID } from "node:crypto";
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { v2 as cloudinary } from "cloudinary";

export const MAX_IMAGE_BYTES = 8 * 1024 * 1024;
const ALLOWED = ["image/jpeg", "image/png", "image/webp", "image/avif"];

export function cloudinaryConfigured() {
  return Boolean(
    process.env.CLOUDINARY_CLOUD_NAME &&
      process.env.CLOUDINARY_API_KEY &&
      process.env.CLOUDINARY_API_SECRET,
  );
}

if (cloudinaryConfigured()) {
  cloudinary.config({
    cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
    api_key: process.env.CLOUDINARY_API_KEY,
    api_secret: process.env.CLOUDINARY_API_SECRET,
    secure: true,
  });
}

function signature(buffer: Buffer) {
  if (buffer.length < 12) return null;
  if (buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) return "image/jpeg";
  if (buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4e && buffer[3] === 0x47) return "image/png";
  if (buffer.subarray(0, 4).toString("ascii") === "RIFF" && buffer.subarray(8, 12).toString("ascii") === "WEBP") {
    return "image/webp";
  }
  if (buffer.subarray(4, 8).toString("ascii") === "ftyp" && buffer.subarray(8, 12).toString("ascii").includes("avif")) {
    return "image/avif";
  }
  return null;
}

const extensions: Record<string, string> = {
  "image/jpeg": "jpg",
  "image/png": "png",
  "image/webp": "webp",
  "image/avif": "avif",
};

export async function uploadImage(file: File): Promise<{ url: string; provider: "cloudinary" | "local" }> {
  if (!ALLOWED.includes(file.type)) {
    throw new Error("Format d'image non pris en charge (JPEG, PNG, WebP ou AVIF).");
  }
  if (file.size <= 0) throw new Error("Fichier vide.");
  if (file.size > MAX_IMAGE_BYTES) throw new Error("Image trop lourde (8 Mo maximum).");

  const buffer = Buffer.from(await file.arrayBuffer());
  const detected = signature(buffer);
  if (!detected || detected !== file.type) {
    throw new Error("Le contenu du fichier ne correspond pas à un format d'image valide.");
  }

  if (cloudinaryConfigured()) {
    const result = await new Promise<{ secure_url: string }>((resolve, reject) => {
      const stream = cloudinary.uploader.upload_stream(
        { folder: "dar-zellige/products", resource_type: "image" },
        (error, uploaded) => {
          if (error || !uploaded) reject(error ?? new Error("Échec de l'upload Cloudinary."));
          else resolve(uploaded as { secure_url: string });
        },
      );
      stream.end(buffer);
    });
    return { url: result.secure_url, provider: "cloudinary" };
  }

  const dir = path.join(process.cwd(), "public", "uploads");
  await mkdir(dir, { recursive: true });
  const filename = `${Date.now()}-${randomUUID().slice(0, 8)}.${extensions[detected]}`;
  await writeFile(path.join(dir, filename), buffer);
  // Served by the dynamic /api/uploads/[file] route: files written after
  // `next build` are not picked up by the static public directory.
  return { url: `/api/uploads/${filename}`, provider: "local" };
}
