import fs from "fs";
import path from "path";

/**
 * Decode a base64 (or data-URI) string and write it as a PNG file to
 * `uploads/<folder>/` inside the project root.
 *
 * @param base64   Raw base64 or data-URI string (e.g. "data:image/png;base64,iVBOR...")
 * @param folder   Sub-folder inside `uploads/`  (e.g. "box-return-signatures")
 * @param prefix   Filename prefix               (e.g. "sig")
 * @returns        The saved filename            (e.g. "sig-1725789123456-847231.png")
 */
export function saveBase64File(
  base64: string,
  folder: string = "box-return-signatures",
  prefix: string = "sig"
): string {
  // Strip optional data-URI header: "data:image/png;base64,<data>"
  const matches = base64.match(/^data:([a-zA-Z0-9]+\/[a-zA-Z0-9+.-]+);base64,(.+)$/);
  const rawBase64 = matches ? matches[2] : base64;

  // Resolve extension from MIME if present, else default to .png
  let ext = ".png";
  if (matches) {
    const mime = matches[1]!; // e.g. "image/jpeg" — guaranteed non-null inside if(matches)
    const mimeExt: { [key: string]: string } = {
      "image/png": ".png",
      "image/jpeg": ".jpg",
      "image/jpg": ".jpg",
      "image/gif": ".gif",
      "image/webp": ".webp",
    };
    ext = mimeExt[mime] ?? ".png";
  }

  // Ensure upload directory exists
  const uploadDir = path.join(process.cwd(), "uploads", folder);
  if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir, { recursive: true });
  }

  // Generate a unique filename
  const unique = `${Date.now()}-${Math.round(Math.random() * 1_000_000)}`;
  const filename = `${prefix}-${unique}${ext}`;
  const filePath = path.join(uploadDir, filename);

  // Write binary buffer
  const buffer = Buffer.from(rawBase64 ?? "", "base64");
  fs.writeFileSync(filePath, buffer);

  return filename;
}

/**
 * Delete a previously saved file from `uploads/<folder>/`.
 * Silently ignores missing files.
 */
export function deleteUploadedFile(filename: string, folder: string): void {
  if (!filename) return;
  const filePath = path.join(process.cwd(), "uploads", folder, filename);
  try {
    if (fs.existsSync(filePath)) {
      fs.unlinkSync(filePath);
    }
  } catch {
    // non-critical — ignore errors
  }
}
