import { NextResponse } from "next/server";
import { getMyinfoConfig } from "@/lib/myinfo-config";
import {
  applicationServiceEnabled,
  getApplicationConfig,
} from "@/lib/application-config";
import { getServerEnvironment } from "@/lib/env";
import { contactProviders } from "@/lib/contact-providers";
import {
  startMyinfo,
  transactionCookie,
  transactionOptions,
} from "@/lib/myinfo-server";
export const runtime = "nodejs";
export async function POST(request: Request) {
  const headers = {
    "Cache-Control": "no-store",
    "Referrer-Policy": "no-referrer",
  };
  try {
    const config = getMyinfoConfig();
    if (!config || !applicationServiceEnabled(getApplicationConfig()))
      return NextResponse.json(
        {
          error:
            "Singpass retrieval is unavailable. Please enter your details manually.",
        },
        { status: 503, headers },
      );
    if (
      request.headers.get("origin") !== config.origin ||
      request.headers.get("sec-fetch-site") === "cross-site"
    )
      return NextResponse.json(
        { error: "Please start again from the application form." },
        { status: 403, headers },
      );
    const limiter = contactProviders(getServerEnvironment(), config.origin);
    const limit = await limiter.consume(`myinfo-${limiter.clientKey(request)}`);
    if (!limit.allowed)
      return NextResponse.json(
        {
          error:
            "Please wait before trying Singpass again, or continue manually.",
        },
        {
          status: 429,
          headers: { ...headers, "Retry-After": String(limit.retryAfter) },
        },
      );
    const result = await startMyinfo(config);
    const response = NextResponse.json({ url: result.url }, { headers });
    response.cookies.set(transactionCookie, result.cookie, {
      ...transactionOptions,
      secure: config.origin.startsWith("https:"),
    });
    return response;
  } catch {
    return NextResponse.json(
      {
        error:
          "Singpass retrieval is unavailable. Please try again or enter your details manually.",
      },
      { status: 503, headers },
    );
  }
}
