import { NextResponse } from "next/server";

import {
  employeeScopeFromAccess,
  requirePermission,
} from "@/lib/authorization";
import {
  DocumentGenerationError,
  generateAttestationImpots,
} from "@/services/impressions.service";
import { attestationImpotsSchema } from "@/validators/impressions";

export const runtime = "nodejs";

function errorResponse(error: DocumentGenerationError) {
  if (error.code === "EMPLOYE_NOT_FOUND") {
    return NextResponse.json({ message: "Employe not found" }, { status: 404 });
  }

  if (error.code === "CONTRACT_NOT_FOUND") {
    return NextResponse.json(
      { message: "No contract found for this employee" },
      { status: 409 },
    );
  }

  if (error.code === "SIGNATAIRE_NOT_FOUND") {
    return NextResponse.json(
      { message: "Active signataire not found" },
      { status: 404 },
    );
  }

  return NextResponse.json(
    {
      message: "Required document data is missing",
      missingFields: error.missingFields,
    },
    { status: 422 },
  );
}

export async function POST(request: Request) {
  const auth = await requirePermission(request, "impressions", "read");

  if (!auth.ok) return auth.response;

  let body: unknown;

  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ message: "Invalid JSON body" }, { status: 400 });
  }

  const parsed = attestationImpotsSchema.safeParse(body);

  if (!parsed.success) {
    return NextResponse.json(
      { message: "Invalid body parameters", issues: parsed.error.issues },
      { status: 400 },
    );
  }

  try {
    const document = await generateAttestationImpots(
      parsed.data.cos,
      parsed.data.signataireId,
      employeeScopeFromAccess(auth.access),
    );
    const filename = `attestation-impots-${parsed.data.cos}.docx`;

    return new NextResponse(new Uint8Array(document), {
      status: 200,
      headers: {
        "Content-Type":
          "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        "Content-Disposition": `attachment; filename="${filename}"`,
        "Cache-Control": "private, no-store",
      },
    });
  } catch (error: unknown) {
    if (error instanceof DocumentGenerationError) {
      return errorResponse(error);
    }

    console.error("Erreur lors de la génération de l'attestation impôts", error);
    return NextResponse.json(
      { message: "Document generation failed" },
      { status: 500 },
    );
  }
}
