import { NextResponse } from "next/server";
import { EterraClient } from "@/modules/parcel-sync/services/eterra-client";
import { getSessionCredentials } from "@/modules/parcel-sync/services/session-store";

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

/**
 * GET /api/eterra/uats/test-counties
 *
 * Diagnostic endpoint: tests eTerra nomenclature API and returns
 * raw results. Hit this from your browser to see exactly what
 * fetchCounties() and fetchAdminUnitsByCounty() return.
 *
 * Requires active eTerra session.
 */
export async function GET() {
  try {
    const session = getSessionCredentials();
    if (!session) {
      return NextResponse.json({
        error: "Nu ești conectat la eTerra.",
        step: "credentials",
      });
    }

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

    // Step 1: Fetch counties
    let rawCounties: unknown;
    try {
      rawCounties = await client.fetchCounties();
    } catch (err) {
      return NextResponse.json({
        error: "fetchCounties() a eșuat",
        step: "fetchCounties",
        message: err instanceof Error ? err.message : String(err),
      });
    }

    const isArray = Array.isArray(rawCounties);
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const countiesArr: any[] = isArray
      ? rawCounties
      : // eslint-disable-next-line @typescript-eslint/no-explicit-any
        Array.isArray((rawCounties as any)?.content)
        ? // eslint-disable-next-line @typescript-eslint/no-explicit-any
          (rawCounties as any).content
        : [];

    const countySummary = {
      rawType: typeof rawCounties,
      isArray,
      unwrappedLength: countiesArr.length,
      topLevelKeys:
        rawCounties && typeof rawCounties === "object" && !isArray
          ? Object.keys(rawCounties)
          : null,
      firstCounty: countiesArr[0]
        ? {
            allKeys: Object.keys(countiesArr[0]),
            raw: countiesArr[0],
          }
        : null,
      // Show first 5 counties
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      first5: countiesArr.slice(0, 5).map((c: any) => ({
        nomenPk: c?.nomenPk,
        name: c?.name,
        nomenName: c?.nomenName,
        label: c?.label,
        code: c?.code,
        allKeys: Object.keys(c ?? {}),
      })),
    };

    // Step 2: Test fetchAdminUnitsByCounty with first county
    let uatSample = null;
    if (countiesArr.length > 0) {
      const firstCountyPk = countiesArr[0]?.nomenPk;
      if (firstCountyPk) {
        try {
          const rawUats =
            await client.fetchAdminUnitsByCounty(firstCountyPk);
          const uatsArr = Array.isArray(rawUats)
            ? rawUats
            : // eslint-disable-next-line @typescript-eslint/no-explicit-any
              Array.isArray((rawUats as any)?.content)
              ? // eslint-disable-next-line @typescript-eslint/no-explicit-any
                (rawUats as any).content
              : [];

          uatSample = {
            countyPk: firstCountyPk,
            countyName: countiesArr[0]?.name,
            rawType: typeof rawUats,
            isArray: Array.isArray(rawUats),
            unwrappedLength: uatsArr.length,
            topLevelKeys:
              rawUats && typeof rawUats === "object" && !Array.isArray(rawUats)
                ? Object.keys(rawUats)
                : null,
            firstUat: uatsArr[0]
              ? {
                  allKeys: Object.keys(uatsArr[0]),
                  raw: uatsArr[0],
                }
              : null,
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            first5: uatsArr.slice(0, 5).map((u: any) => ({
              nomenPk: u?.nomenPk,
              name: u?.name,
              nomenName: u?.nomenName,
              code: u?.code,
              sirutaCode: u?.sirutaCode,
              allKeys: Object.keys(u ?? {}),
            })),
          };
        } catch (err) {
          uatSample = {
            error: "fetchAdminUnitsByCounty() a eșuat",
            message: err instanceof Error ? err.message : String(err),
          };
        }
      }
    }

    return NextResponse.json({
      status: "ok",
      counties: countySummary,
      uatSample,
    });
  } catch (error) {
    return NextResponse.json({
      error: "Eroare generală",
      message: error instanceof Error ? error.message : String(error),
    });
  }
}
