import {
  applicationServiceEnabled,
  getApplicationConfig,
} from "@/lib/application-config";
import { randomBytes } from "node:crypto";
import { NextRequest, NextResponse } from "next/server";
import { getMyinfoConfig } from "@/lib/myinfo-config";
import {
  finishMyinfo,
  transactionCookie,
  transactionOptions,
} from "@/lib/myinfo-server";
export const runtime = "nodejs";
export async function GET(request: NextRequest) {
  let origin = new URL(request.url).origin;
  let result: object = {
    error:
      "Retrieval was cancelled, expired or could not be completed. Please try again or enter your details manually.",
  };
  try {
    const config = getMyinfoConfig();
    if (!config) throw new Error();
    const application = getApplicationConfig();
    if (!applicationServiceEnabled(application)) throw new Error();
    origin = config.origin;
    const url = new URL(config.redirectUri);
    url.search = request.nextUrl.search;
    result = {
      profile: await finishMyinfo(
        config,
        url,
        request.cookies.get(transactionCookie)?.value ?? "",
        application.APPLICATION_SIGNING_SECRET,
      ),
    };
  } catch {}
  const nonce = randomBytes(24).toString("base64");
  const payload = JSON.stringify({
    type: "maxcredit-myinfo",
    ...result,
  }).replaceAll("<", "\\u003c");
  const html = `<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Return to your application</title><body><h1>Return to your application</h1><p>You can close this window and return to your application to review your details or try again.</p><a href="/apply">Open application</a><script nonce="${nonce}">if(window.opener){window.opener.postMessage(${payload},${JSON.stringify(origin)});window.close();}history.replaceState(null,"","/api/myinfo/callback");</script></body></html>`;
  const response = new NextResponse(html, {
    headers: {
      "Content-Type": "text/html; charset=utf-8",
      "Cache-Control": "no-store, private",
      "Referrer-Policy": "no-referrer",
      "X-Robots-Tag": "noindex, nofollow",
      "Content-Security-Policy": `default-src 'none'; script-src 'nonce-${nonce}'; base-uri 'none'; frame-ancestors 'none'`,
      "X-Content-Type-Options": "nosniff",
    },
  });
  response.cookies.set(transactionCookie, "", {
    ...transactionOptions,
    secure: origin.startsWith("https:"),
    maxAge: 0,
  });
  return response;
}
