// Consolidated upload size/type validation (Wertstrom P6, Review-Fix
// C7+C13+C14+C19, adversarial review PR #360). ONE shared classifier used by
// BOTH app/api/wertstrom/import/preview/route.ts (many files, .json+.svg
// mixed) and .../confirm/route.ts (one re-uploaded .json file) — previously
// each route re-implemented its own ad hoc size check, and the preview route
// conflated "wrong extension" with "too big" into the identical response
// shape (a 200-byte .txt got told it was "zu groß", which is simply false).
//
// Order matters and is enforced by classifyUploadFile itself: extension/
// type FIRST (own message), THEN the per-file size limit (own message) —
// never "zu groß" for a file whose real problem is its extension. The
// TOTAL-across-all-files check (checkTotalUploadSize) is a separate,
// explicit step callers run once every individual file already passed
// classifyUploadFile.
//
// SVG had NO size check at all before this fix (lib/simvsm-import/README.md
// "SVG is metadata-only" only ever justified server MEMORY cost — a file's
// name-only read — never the actual multipart HTTP body size the client
// still uploads in full). It now gets its own (smaller — SVGs are metadata-
// only, a large one is almost certainly not "just a diagram") per-file cap.

export const JSON_FILE_MAX_BYTES = 4 * 1024 * 1024 // 4 MB — unchanged from the original per-file JSON limit (README.md "Größenlimit / Body-Limit").
export const SVG_FILE_MAX_BYTES = 2 * 1024 * 1024 // 2 MB — SVG bytes are never read (name-only, see families.ts), but they still count against the shared multipart request body.

// Vercel's Node.js Serverless Function request body cap is ~4.5 MB
// (platform-level, not configurable via next.config.mjs — see README.md).
// TOTAL_REQUEST_MAX_BYTES stays honestly BELOW that hard cap (not AT it) —
// multipart framing/field boundaries/headers add overhead on top of the raw
// file bytes summed by checkTotalUploadSize, and this repo also deploys to
// Docker/Azure Container Apps (DEPLOYMENT.md), which does NOT share Vercel's
// specific cap at all — without an application-level total check, an
// Azure-hosted deployment would have no total-size guard whatsoever.
export const TOTAL_REQUEST_MAX_BYTES = 4.2 * 1024 * 1024 // 4.2 MB — headroom above the single JSON_FILE_MAX_BYTES case (JSON near its own cap + a small SVG), safely under Vercel's ~4.5 MB hard cap.

export type UploadFileKind = 'json' | 'svg'
export type UploadRejectionReason = 'unsupported_extension' | 'oversized'

export interface UploadFileCheckInput {
  fileName: string
  sizeBytes: number
}

export type UploadFileCheckResult =
  | { ok: true; kind: UploadFileKind }
  | { ok: false; reason: UploadRejectionReason; fileName: string; sizeBytes: number; limitBytes: number; messageDe: string }

function formatMB(bytes: number): string {
  const mb = Math.round((bytes / (1024 * 1024)) * 10) / 10
  return `${mb} MB`
}

/** Per-file check ONLY (extension/type, then the per-file size limit) —
 * never checks the running total across multiple files, see
 * checkTotalUploadSize for that. */
export function classifyUploadFile({ fileName, sizeBytes }: UploadFileCheckInput): UploadFileCheckResult {
  if (/\.json$/i.test(fileName)) {
    if (sizeBytes > JSON_FILE_MAX_BYTES) {
      return {
        ok: false,
        reason: 'oversized',
        fileName,
        sizeBytes,
        limitBytes: JSON_FILE_MAX_BYTES,
        messageDe: `„${fileName}“ (${formatMB(sizeBytes)}) überschreitet das Limit von ${formatMB(JSON_FILE_MAX_BYTES)} für JSON-Dateien.`,
      }
    }
    return { ok: true, kind: 'json' }
  }
  if (/\.svg$/i.test(fileName)) {
    if (sizeBytes > SVG_FILE_MAX_BYTES) {
      return {
        ok: false,
        reason: 'oversized',
        fileName,
        sizeBytes,
        limitBytes: SVG_FILE_MAX_BYTES,
        messageDe: `„${fileName}“ (${formatMB(sizeBytes)}) überschreitet das Limit von ${formatMB(SVG_FILE_MAX_BYTES)} für SVG-Dateien.`,
      }
    }
    return { ok: true, kind: 'svg' }
  }
  return {
    ok: false,
    reason: 'unsupported_extension',
    fileName,
    sizeBytes,
    limitBytes: 0,
    messageDe: `„${fileName}“ hat eine nicht unterstützte Dateiendung — nur .json und .svg sind möglich.`,
  }
}

/** Total-across-all-files check — call once, after every individual file
 * already passed classifyUploadFile (or in parallel/upfront, using each
 * File's already-known `.size`; reading `.size` never requires reading
 * bytes). A single, honest rejection message — never a silent partial
 * truncation, never the platform's own opaque body-cap error. */
export function checkTotalUploadSize(totalBytes: number): { ok: true } | { ok: false; messageDe: string } {
  if (totalBytes > TOTAL_REQUEST_MAX_BYTES) {
    return {
      ok: false,
      messageDe: `Die ausgewählten Dateien überschreiten zusammen ${formatMB(TOTAL_REQUEST_MAX_BYTES)} (Gesamtlimit für einen Import-Vorgang) — bitte in kleineren Gruppen hochladen.`,
    }
  }
  return { ok: true }
}
