import { NextRequest, NextResponse } from "next/server";
import { EterraClient } from "@/modules/parcel-sync/services/eterra-client";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

/**
 * GET /api/eterra/rgi/details?applicationId=...
 *
 * Fetch RGI application details by application ID.
 * Proxies eTerra rgi/appdetail/details endpoint.
 */
export async function GET(req: NextRequest) {
  try {
    const applicationId = req.nextUrl.searchParams.get("applicationId");

    if (!applicationId) {
      return NextResponse.json(
        { error: "applicationId is required" },
        { status: 400 },
      );
    }

    const username = process.env.ETERRA_USERNAME ?? "";
    const password = process.env.ETERRA_PASSWORD ?? "";
    if (!username || !password) {
      return NextResponse.json(
        { error: "Credentials missing" },
        { status: 500 },
      );
    }

    const client = await EterraClient.create(username, password);

    const result = await client.rgiPost(
      `rgi/appdetail/details?applicationid=${encodeURIComponent(applicationId)}`,
      undefined,
    );

    return NextResponse.json(result);
  } catch (error) {
    const message = error instanceof Error ? error.message : "Eroare server";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
