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/issued-docs?applicationId=...&workspaceId=...
 *
 * List issued documents for an RGI application.
 * Proxies eTerra rgi/appdetail/issueddocs/list endpoint.
 */
export async function GET(req: NextRequest) {
  try {
    const applicationId = req.nextUrl.searchParams.get("applicationId");
    const workspaceId = req.nextUrl.searchParams.get("workspaceId");

    if (!applicationId || !workspaceId) {
      return NextResponse.json(
        { error: "applicationId and workspaceId are 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/issueddocs/list?applicationid=${encodeURIComponent(applicationId)}&reSaveDocsInPendingAndTiomeOut=false&workspaceid=${encodeURIComponent(workspaceId)}`,
      {
        filters: [],
        sorters: [],
        nrElements: 50,
        page: 0,
      },
    );

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