import { NextResponse } from "next/server";
import {
  hashAadhaar,
  isValidAadhaarFormat,
  isValidIndianMobile,
  normalizeAadhaar,
  normalizeMobile,
} from "@/lib/aadhaar";
import { aadhaarExists } from "@/lib/visitors";
import { createOtpSession } from "@/lib/otp";
import { auditLog } from "@/lib/audit";
import { evaluateHuman, humanRejectResponse } from "@/lib/human";
import { requestMeta } from "@/lib/request-meta";
import {
  recordHumanCheckReject,
  withRegistrationSecurity,
} from "@/lib/security";
import { safeError } from "@/lib/safe-log";

export async function POST(req: Request) {
  return withRegistrationSecurity(
    req,
    {
      routeGroup: "registration",
      pathNorm: "/api/v1/registration/otp/send",
    },
    async () => {
      const meta = requestMeta(req);
      try {
        const body = await req.json();
        const human = evaluateHuman(body.human);
        if (!human.ok) {
          await auditLog({
            step: "human_check",
            outcome: "reject",
            ip: meta.ip,
            userAgent: meta.userAgent,
            meta: { reason: human.reason, score: human.score, at: "otp_send" },
          });
          recordHumanCheckReject({
            at: "otp_send",
            reason: human.reason,
            score: human.score,
            sourceIp: meta.ip,
          });
          return NextResponse.json(humanRejectResponse(human.reason), {
            status: 403,
          });
        }

        const aadhaar = normalizeAadhaar(String(body.aadhaar_number || ""));
        const mobile = normalizeMobile(String(body.mobile || ""));

        if (!isValidAadhaarFormat(aadhaar)) {
          await auditLog({
            step: "otp_send",
            outcome: "invalid_aadhaar",
            ip: meta.ip,
            userAgent: meta.userAgent,
          });
          return NextResponse.json(
            { ok: false, error: "The Aadhaar number appears to be incorrect." },
            { status: 400 },
          );
        }
        if (!isValidIndianMobile(mobile)) {
          await auditLog({
            step: "otp_send",
            outcome: "invalid_mobile",
            ip: meta.ip,
            userAgent: meta.userAgent,
          });
          return NextResponse.json(
            { ok: false, error: "Enter a valid 10-digit Indian mobile number." },
            { status: 400 },
          );
        }

        const existing = await aadhaarExists(hashAadhaar(aadhaar));
        if (existing) {
          await auditLog({
            step: "otp_send",
            outcome: "duplicate",
            ip: meta.ip,
            userAgent: meta.userAgent,
            meta: { pass_no: existing },
          });
          return NextResponse.json(
            {
              ok: false,
              error: "This Aadhaar is already registered.",
              pass_no: existing,
            },
            { status: 409 },
          );
        }

        const session = await createOtpSession(aadhaar, mobile);
        await auditLog({
          step: "otp_send",
          outcome: "sent",
          ip: meta.ip,
          userAgent: meta.userAgent,
          meta: {
            mobile_masked: `${mobile.slice(0, 2)}XXXXXX${mobile.slice(-2)}`,
            human_score: human.score,
          },
        });

        return NextResponse.json({
          ok: true,
          session_id: session.sessionId,
          expires_at: session.expiresAt,
          message: "A six-digit verification code has been sent to your mobile.",
          ...(session.devOtp ? { dev_otp: session.devOtp } : {}),
        });
      } catch (e) {
        safeError(e);
        return NextResponse.json(
          { ok: false, error: "Unable to send OTP right now." },
          { status: 500 },
        );
      }
    },
  );
}
