import { NextResponse } from "next/server";
import { promises as fs } from "node:fs";
import path from "node:path";
import { eq } from "drizzle-orm";
import { db, schema } from "@/lib/db";
import type { DocumentRequest } from "@/lib/forms/types";

const UPLOADS_DIR =
  process.env.UPLOADS_DIR || path.join(process.cwd(), "uploads");

/**
 * Télécharge le fichier exemple attaché à un documentRequest d'un service.
 * Public : pas d'auth requise (les fichiers sont des modèles à diffuser).
 *
 * On sert avec Content-Disposition: attachment + on lit le path depuis
 * la DB pour empêcher tout path traversal arbitraire.
 */
export async function GET(
  _req: Request,
  { params }: { params: Promise<{ slug: string; docId: string }> }
) {
  const { slug, docId } = await params;

  const tpl = (
    await db
      .select()
      .from(schema.formTemplate)
      .where(eq(schema.formTemplate.serviceSlug, slug))
      .limit(1)
  )[0];

  if (!tpl || !tpl.published) {
    return NextResponse.json({ error: "Template introuvable" }, { status: 404 });
  }

  const docs = (tpl.documentRequests as DocumentRequest[]) ?? [];
  const doc = docs.find((d) => d.id === docId);
  if (!doc?.sampleFile) {
    return NextResponse.json({ error: "Document introuvable" }, { status: 404 });
  }

  const sample = doc.sampleFile;
  // Sécurité : on n'autorise que les paths préfixés _samples/
  if (!sample.path.startsWith("_samples/")) {
    return NextResponse.json({ error: "Path invalide" }, { status: 400 });
  }

  const abs = path.join(UPLOADS_DIR, sample.path);
  try {
    const bytes = await fs.readFile(abs);
    const arrayBuffer = bytes.buffer.slice(
      bytes.byteOffset,
      bytes.byteOffset + bytes.byteLength
    );
    return new NextResponse(arrayBuffer as ArrayBuffer, {
      status: 200,
      headers: {
        "Content-Type": sample.mimeType ?? "application/octet-stream",
        "Content-Length": String(bytes.byteLength),
        "Content-Disposition": `attachment; filename="${encodeURIComponent(sample.name)}"`,
        "Cache-Control": "public, max-age=300",
      },
    });
  } catch {
    return NextResponse.json({ error: "Fichier introuvable" }, { status: 404 });
  }
}
