import { getSessionUser } from "@/lib/auth";
import { getAppSessionUserByToken, readAppBearerToken } from "@/lib/app-auth";
import {
  abortDirectLargeComposeAttachmentForUserEmail,
  completeDirectLargeComposeAttachmentForUserEmail,
  startDirectLargeComposeAttachmentForUserEmail,
} from "@/lib/mail-compose-uploads";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

async function authenticatedEmail(request: Request) {
  const user = (await getSessionUser()) ??
    (await getAppSessionUserByToken(readAppBearerToken(request.headers), request.headers));
  return user?.email ?? null;
}

async function smallJsonBody(request: Request): Promise<Record<string, unknown> | null> {
  const length = Number(request.headers.get("content-length") ?? "0");
  if (length > 4096) return null;
  try {
    const body: unknown = await request.json();
    return body && typeof body === "object" && !Array.isArray(body)
      ? body as Record<string, unknown>
      : null;
  } catch {
    return null;
  }
}

export async function POST(request: Request) {
  const email = await authenticatedEmail(request);
  if (!email) return Response.json({ error: "unauthorized" }, { status: 401 });
  const body = await smallJsonBody(request);
  if (!body) return Response.json({ error: "invalid-request" }, { status: 400 });
  try {
    if (body.action === "start" && typeof body.filename === "string" &&
        typeof body.contentType === "string" && typeof body.sizeBytes === "number") {
      const session = await startDirectLargeComposeAttachmentForUserEmail({
        contentType: body.contentType,
        email,
        filename: body.filename,
        sizeBytes: body.sizeBytes,
      });
      return Response.json(session, { headers: { "Cache-Control": "no-store" } });
    }
    if (body.action === "complete" && typeof body.token === "string" &&
        /^[a-f0-9]{48}$/.test(body.token)) {
      const uploaded = await completeDirectLargeComposeAttachmentForUserEmail({ email, token: body.token });
      return Response.json(uploaded, { headers: { "Cache-Control": "no-store" } });
    }
    return Response.json({ error: "invalid-request" }, { status: 400 });
  } catch (error) {
    const code = error instanceof Error ? error.message : "upload-failed";
    if (code === "attachment-growth-required") return Response.json({ error: code }, { status: 403 });
    if (code === "attachment-drawer-quota") return Response.json({ error: code }, { status: 409 });
    if (code === "attachment-large-limit") return Response.json({ error: code }, { status: 413 });
    if (["upload-parts-incomplete", "upload-size-mismatch", "upload-session-unavailable"].includes(code)) {
      return Response.json({ error: code }, { status: 409 });
    }
    console.error("[compose-direct-large-upload] failed", code);
    return Response.json({ error: "upload-failed" }, { status: 503 });
  }
}

export async function DELETE(request: Request) {
  const email = await authenticatedEmail(request);
  if (!email) return Response.json({ error: "unauthorized" }, { status: 401 });
  const body = await smallJsonBody(request);
  if (!body || typeof body.token !== "string" || !/^[a-f0-9]{48}$/.test(body.token)) {
    return Response.json({ error: "invalid-request" }, { status: 400 });
  }
  await abortDirectLargeComposeAttachmentForUserEmail({ email, token: body.token });
  return Response.json({ aborted: true }, { headers: { "Cache-Control": "no-store" } });
}
