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

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

type Body = {
  workspaceId: number;
  orgUnitId: number;
  year: string;
  page?: number;
  nrElements?: number;
};

/**
 * POST /api/eterra/rgi/applications
 *
 * List RGI applications for a given workspace (county) and org unit (UAT).
 * Proxies eTerra rgi/applicationgrid/list endpoint.
 */
export async function POST(req: NextRequest) {
  try {
    const body = (await req.json()) as Body;
    const { workspaceId, orgUnitId, year } = body;

    if (!workspaceId || !orgUnitId || !year) {
      return NextResponse.json(
        { error: "workspaceId, orgUnitId and year 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 page = body.page ?? 0;
    const nrElements = body.nrElements ?? 25;

    const payload = {
      filters: [
        {
          value: workspaceId,
          type: "NUMBER",
          key: "workspace.nomenPk",
          op: "=",
        },
        {
          value: orgUnitId,
          type: "NUMBER",
          key: "partyFunctionByOrgUnitId.nomenPk",
          op: "=",
        },
      ],
      applicationFilters: {
        applicationType: "own",
        tabCode: "NUMBER_LIST",
        year,
        countyId: workspaceId,
        adminUnitId: orgUnitId,
        showAll: false,
        showNewRequests: false,
        showSuspended: false,
        showSolutionDeadlineExpired: false,
        showPendingLimitation: false,
        showCadastreNumberAllocated: false,
        showImmovableRegistered: false,
        showDocumentIssued: false,
        showRestitutionClosed: false,
        showRejected: false,
        showClosed: false,
        showWithdrawn: false,
        showSolutionDeadlineExceeded: false,
      },
      sorters: [],
      nrElements,
      page,
    };

    const result = await client.rgiPost(
      "rgi/applicationgrid/list",
      payload,
    );

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