import { applicationProviders } from "@/lib/application-providers";
import {
  applicationBody,
  applicationReply,
  applicationRoute,
} from "@/lib/application-http";
import {
  ApplicationError,
  prepareApplicationSchema,
} from "@/lib/application-record";
import { prepareApplication } from "@/lib/application-service";
import { declarationVersionOutdated } from "@/lib/application-declaration";
export const runtime = "nodejs";
export async function POST(request: Request) {
  return applicationRoute(async () => {
    const providers = applicationProviders();
    const body = await applicationBody(request, providers.origin, 524288);
    if (declarationVersionOutdated(body))
      throw new ApplicationError(
        409,
        "The application declarations were updated. Reload this page, then select Check result and edit.",
      );
    const parsed = prepareApplicationSchema.safeParse(body);
    if (!parsed.success)
      throw new ApplicationError(
        400,
        "Check the application details and security check.",
      );
    await providers.limit(request);
    if (!(await providers.verify(parsed.data.turnstileToken)))
      throw new ApplicationError(400, "Complete the security check again.");
    return applicationReply(await prepareApplication(parsed.data, providers));
  });
}
