import type { FastifyRequest } from "fastify";
import { createHash, randomUUID } from "node:crypto";
import { createReadStream, createWriteStream } from "node:fs";
import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
import type { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";
import { dirname, resolve, sep } from "node:path";
import { env } from "../../config/env.js";
import { sha256 } from "../crypto.js";
import { insert, one, pool, type Db } from "../db/db.js";
import { DomainError } from "../http/errors.js";

const KINDS: Record<string, { ext: RegExp; magic: (b: Buffer) => boolean; mime: string }> = {
  pdf: { ext: /\.pdf$/i, magic: (b) => b.subarray(0, 4).toString() === "%PDF", mime: "application/pdf" },
  jpg: { ext: /\.jpe?g$/i, magic: (b) => b[0] === 0xff && b[1] === 0xd8, mime: "image/jpeg" },
  png: { ext: /\.png$/i, magic: (b) => b.subarray(1, 4).toString() === "PNG", mime: "image/png" },
  office: { ext: /\.(docx|xlsx|pptx|zip)$/i, magic: (b) => b[0] === 0x50 && b[1] === 0x4b, mime: "application/octet-stream" },
  old: { ext: /\.(doc|xls)$/i, magic: (b) => b[0] === 0xd0 && b[1] === 0xcf, mime: "application/octet-stream" },
  csv: { ext: /\.(csv|txt)$/i, magic: (b) => !b.subarray(0, 2000).includes(0), mime: "text/csv" },
};
const path = (key: string) => {
  const root = resolve(env.STORAGE_DIR), p = resolve(root, key);
  if (!p.startsWith(root + sep)) throw new Error("path escapes storage");
  return p;
};
/** Evidence may be of any type, as in V1, except programs and pages that could run on the reader's computer. */
const DANGEROUS = /\.(exe|com|bat|cmd|msi|scr|pif|cpl|dll|jar|js|mjs|vbs|vbe|wsf|hta|ps1|psm1|sh|php|lnk|reg|html?|xhtml|svg|apk|app|dmg|iso)$/i;
export const INCOMING = ".incoming", MAX_EVIDENCE_MB = 100;
/** A large upload, already on disk but not yet part of any record. */
export interface Incoming { name: string; temp: string; size: number; sha256: string; head: Buffer }
/** Reads evidence straight to disk, so large files never fill the memory. Call `clean` when done. */
export async function receive(req: FastifyRequest, maxFiles: number): Promise<{ fields: Record<string, string>; files: Incoming[]; clean: () => Promise<void> }> {
  if (!req.isMultipart()) throw new DomainError(415, "FILE_EXPECTED", "Send a file.");
  const dir = path(INCOMING), fields: Record<string, string> = {}, files: Incoming[] = [], temps: string[] = [];
  const clean = async () => { for (const t of temps) await rm(t, { force: true }); };
  await mkdir(dir, { recursive: true });
  // What a crash left behind.
  for (const n of await readdir(dir)) { const s = await stat(`${dir}${sep}${n}`).catch(() => null); if (s && s.mtimeMs < Date.now() - 86_400_000) await rm(`${dir}${sep}${n}`, { force: true }); }
  try {
    for await (const part of req.parts({ limits: { fileSize: MAX_EVIDENCE_MB * 1024 * 1024, files: maxFiles } })) {
      if (part.type !== "file") { fields[part.fieldname] = String(part.value); continue; }
      if (!part.filename) { part.file.resume(); continue; }
      const temp = resolve(dir, randomUUID()), hash = createHash("sha256"), head: Buffer[] = [];
      let size = 0, kept = 0;
      temps.push(temp);
      part.file.on("data", (b: Buffer) => { hash.update(b); size += b.length; if (kept < 2000) { head.push(b.subarray(0, 2000 - kept)); kept += b.length; } });
      await pipeline(part.file, createWriteStream(temp, { flags: "wx" }));
      if (part.file.truncated) throw new DomainError(413, "FILE_TOO_LARGE", `${part.filename} is larger than ${MAX_EVIDENCE_MB} MB.`);
      files.push({ name: part.filename, temp, size, sha256: hash.digest("hex"), head: Buffer.concat(head) });
    }
  } catch (e) {
    await clean();
    const code = (e as { code?: string }).code;
    if (code === "FST_REQ_FILE_TOO_LARGE") throw new DomainError(413, "FILE_TOO_LARGE", `A file is larger than ${MAX_EVIDENCE_MB} MB.`);
    if (code === "FST_FILES_LIMIT") throw new DomainError(413, "TOO_MANY_FILES", `Send at most ${maxFiles} files at a time.`);
    throw e;
  }
  return { fields, files, clean };
}
/** Takes a received file into storage. */
export async function storeEvidence(db: Db, f: { projectId: string; purpose: "activity_evidence" | "verification_evidence"; file: Incoming; userId: string }): Promise<string> {
  const { name, size, head } = f.file, kind = Object.values(KINDS).find((k) => k.ext.test(name));
  if (!size) throw new DomainError(422, "FILE_EMPTY", `${name} is empty.`);
  if (DANGEROUS.test(name) || head.subarray(0, 2).toString("latin1") === "MZ" || (kind && !kind.magic(head))) throw new DomainError(422, "FILE_TYPE", `${name} is not a file type we accept, or its content does not match its name.`);
  const key = `${f.purpose}/${f.projectId}/${randomUUID()}`;
  await mkdir(dirname(path(key)), { recursive: true });
  await rename(f.file.temp, path(key));
  return insert(db, "files", { project_id: f.projectId, purpose: f.purpose, storage_key: key, original_name: name.length > 190 ? name.slice(0, 180) + (/\.\w{1,9}$/.exec(name)?.[0] ?? "") : name, mime_type: kind?.mime ?? "application/octet-stream", size_bytes: size, sha256: f.file.sha256, uploaded_by: f.userId });
}
/** Opens a stored file for download, after checking that it is still the file that was uploaded. */
export async function openFile(fileId: string): Promise<{ name: string; mime: string; size: number; data: Readable }> {
  const f = await one(pool, "SELECT * FROM files WHERE id=? AND deleted_at IS NULL", [fileId]);
  if (!f) throw new DomainError(404, "NOT_FOUND", "File was not found.");
  const p = path(f["storage_key"]), size = (await stat(p).catch(() => { throw new DomainError(404, "FILE_MISSING", "The file is not in storage."); })).size;
  if (f["sha256"]) { const h = createHash("sha256"); await pipeline(createReadStream(p), h); if (h.digest("hex") !== f["sha256"]) throw new DomainError(409, "FILE_CHANGED", "The stored file no longer matches its checksum."); }
  return { name: f["original_name"], mime: f["mime_type"] ?? "application/octet-stream", size, data: createReadStream(p) };
}
/** The type is decided by the bytes, not by what the browser claims. */
export async function storeFile(db: Db, f: { projectId: string; purpose: string; name: string; data: Buffer; userId: string | null; trusted?: boolean }): Promise<string> {
  const kind = Object.values(KINDS).find((k) => k.ext.test(f.name));
  if (!f.data.length) throw new DomainError(422, "FILE_EMPTY", `${f.name} is empty.`);
  if (!f.trusted && (!kind || !kind.magic(f.data))) throw new DomainError(422, "FILE_TYPE", `${f.name} is not a file type we accept, or its content does not match its name.`);
  const key = `${f.purpose}/${f.projectId}/${randomUUID()}`;
  await mkdir(dirname(path(key)), { recursive: true });
  await writeFile(path(key), f.data, { flag: "wx" });
  return insert(db, "files", { project_id: f.projectId, purpose: f.purpose, storage_key: key, original_name: f.name.slice(0, 190), mime_type: kind?.mime ?? "application/octet-stream", size_bytes: f.data.length, sha256: sha256(f.data), uploaded_by: f.userId });
}
export async function loadFile(fileId: string): Promise<{ name: string; mime: string; data: Buffer }> {
  const f = await one(pool, "SELECT * FROM files WHERE id=? AND deleted_at IS NULL", [fileId]);
  if (!f) throw new DomainError(404, "NOT_FOUND", "File was not found.");
  const data = await readFile(path(f["storage_key"])).catch(() => { throw new DomainError(404, "FILE_MISSING", "The file is not in storage."); });
  if (f["sha256"] && sha256(data) !== f["sha256"]) throw new DomainError(409, "FILE_CHANGED", "The stored file no longer matches its checksum.");
  return { name: f["original_name"], mime: f["mime_type"] ?? "application/octet-stream", data };
}
