import { getSessionUser } from "@/lib/auth";
import {
  deleteComposeUploadByTokenForUserEmail,
  getComposeUploadPayloadByTokenForUserEmail,
} from "@/lib/mail-compose-uploads";

export const runtime = "nodejs";

function buildContentDisposition(filename: string, inline: boolean) {
  const safeAscii = filename.replace(/[^\x20-\x7E]+/g, "_").replace(/["\\]/g, "_") || "upload";
  const encoded = encodeURIComponent(filename);
  const dispositionType = inline ? "inline" : "attachment";

  return `${dispositionType}; filename="${safeAscii}"; filename*=UTF-8''${encoded}`;
}

export async function GET(
  _request: Request,
  context: { params: Promise<{ token: string }> },
) {
  const user = await getSessionUser();

  if (!user) {
    return Response.json({ error: "unauthorized" }, { status: 401 });
  }

  const { token } = await context.params;
  const payload = await getComposeUploadPayloadByTokenForUserEmail(user.email, token);

  if (!payload) {
    return Response.json({ error: "not-found" }, { status: 404 });
  }

  if (!payload.content && payload.publicUrl) {
    return Response.redirect(payload.publicUrl, 302);
  }

  if (!payload.content) {
    return Response.json({ error: "not-found" }, { status: 404 });
  }

  const normalizedContentType = payload.contentType.toLowerCase();
  const inline =
    normalizedContentType.startsWith("image/") ||
    normalizedContentType.startsWith("text/") ||
    normalizedContentType === "application/pdf";

  return new Response(new Uint8Array(payload.content), {
    headers: {
      "Cache-Control": "private, max-age=60",
      "Content-Disposition": buildContentDisposition(payload.filename, inline),
      "Content-Length": String(payload.content.length),
      "Content-Type": payload.contentType || "application/octet-stream",
      "X-Content-Type-Options": "nosniff",
    },
  });
}

export async function DELETE(
  _request: Request,
  context: { params: Promise<{ token: string }> },
) {
  const user = await getSessionUser();

  if (!user) {
    return Response.json({ error: "unauthorized" }, { status: 401 });
  }

  const { token } = await context.params;
  const deleted = await deleteComposeUploadByTokenForUserEmail(user.email, token);

  return Response.json({ ok: deleted });
}
