import type { Context, Next } from "@wrnexus/core";
import { captchaGuard } from "@wrnexus/captcha/server";
import { captchaEngine } from "../lib/captcha.ts";

const protectLogin = captchaGuard({
  action: "auth-login",
  engine: captchaEngine,
  responseField: "wrn-captcha-response",
  bindHostname: true,
  bindSession: true,
  verifiedForMs: 5 * 60_000,
  onFailure(_ctx, result) {
    return Response.json(
      {
        ok: false,
        code: result.code ?? "captcha-invalid",
        message: result.message ?? "Complete the security check below before signing in.",
      },
      {
        status: 403,
        headers: { "cache-control": "no-store" },
      },
    );
  },
});

export default function captchaLogin(ctx: Context, next: Next) {
  return ctx.req.method === "POST" && ctx.url.pathname === "/api/auth/login"
    ? protectLogin(ctx, next)
    : next();
}
