import { auth } from "@/auth";
import { hasPermission } from "@/lib/permissions";
import { NextRequest, NextResponse } from "next/server";

const EPFO_SERVICE = process.env.EPFO_SERVICE_URL ?? "http://localhost:3004";

/** POST /api/epfo { sessionId, uan, otp } → { matched, name, status } — submit the OTP. */
export async function POST(req: NextRequest) {
  const session = await auth();
  if (!session?.user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  if (!hasPermission(session.user.role, "verify_bank_epf")) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  const body = await req.json().catch(() => ({}));
  if (!body.sessionId || !body.uan || !body.otp) {
    return NextResponse.json({ error: "sessionId, uan and otp are required" }, { status: 400 });
  }

  try {
    const res = await fetch(`${EPFO_SERVICE}/verify`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ sessionId: body.sessionId, uan: body.uan, otp: body.otp }),
      cache: "no-store",
    });
    const data = await res.json();
    return NextResponse.json(data, { status: res.ok ? 200 : res.status });
  } catch (e) {
    return NextResponse.json({ error: `EPFO service unavailable: ${String(e)}` }, { status: 502 });
  }
}
