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/otp { uan } → { sessionId, mobileHint } — request an EPFO 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.uan) return NextResponse.json({ error: "uan is required" }, { status: 400 });

  try {
    const res = await fetch(`${EPFO_SERVICE}/otp`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ uan: body.uan }),
      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 });
  }
}
