import "server-only";

import { createHash, randomUUID } from "node:crypto";
import { mkdir, unlink, writeFile } from "node:fs/promises";
import path from "node:path";

export const MAX_ACTA_PDF_BYTES = 15 * 1024 * 1024;

const ACTA_STORAGE_ROOT = path.join(process.cwd(), "storage", "actas");

export type StoredActaPdf = {
  fileName: string;
  storedFileName: string;
  filePath: string;
  mimeType: string;
  sizeBytes: number;
  checksumSha256: string;
};

function sanitizeFileName(input: string) {
  const normalized = input.trim().toLowerCase().replace(/[^a-z0-9._-]+/g, "-");
  const fallback = normalized || "acta-constitutiva.pdf";
  return fallback.endsWith(".pdf") ? fallback : `${fallback}.pdf`;
}

export async function storeActaPdf(userId: string, originalFileName: string, pdfBuffer: Buffer): Promise<StoredActaPdf> {
  const safeOriginalName = sanitizeFileName(originalFileName);
  const userDirectory = path.join(ACTA_STORAGE_ROOT, userId);
  const storedFileName = `${Date.now()}-${randomUUID()}.pdf`;
  const absoluteFilePath = path.join(userDirectory, storedFileName);

  await mkdir(userDirectory, { recursive: true });
  await writeFile(absoluteFilePath, pdfBuffer);

  return {
    fileName: safeOriginalName,
    storedFileName,
    filePath: path.join("storage", "actas", userId, storedFileName).replace(/\\/g, "/"),
    mimeType: "application/pdf",
    sizeBytes: pdfBuffer.byteLength,
    checksumSha256: createHash("sha256").update(pdfBuffer).digest("hex"),
  };
}

export async function removeStoredActaPdf(relativeFilePath: string | null | undefined) {
  if (!relativeFilePath) {
    return;
  }

  const storageRoot = path.resolve(process.cwd(), "storage");
  const absolutePath = path.resolve(process.cwd(), relativeFilePath);

  if (!absolutePath.startsWith(`${storageRoot}${path.sep}`)) {
    return;
  }

  try {
    await unlink(absolutePath);
  } catch {
    // Ignore delete errors (already deleted or inaccessible).
  }
}
