import { NextResponse } from "next/server";
import { getEpayCredentials } from "@/modules/parcel-sync/services/epay-session-store";
import {
  enqueueOrder,
  enqueueBatch,
} from "@/modules/parcel-sync/services/epay-queue";
import type { CfExtractCreateInput } from "@/modules/parcel-sync/services/epay-types";

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

/* ------------------------------------------------------------------ */
/*  Nonce-based idempotency cache                                      */
/* ------------------------------------------------------------------ */

type NonceEntry = {
  timestamp: number;
  response: { orders: Array<{ id: string; nrCadastral: string; status: string }> };
};

const NONCE_TTL_MS = 60_000; // 60 seconds

const gNonce = globalThis as {
  __orderNonceMap?: Map<string, NonceEntry>;
};
if (!gNonce.__orderNonceMap) gNonce.__orderNonceMap = new Map();

function cleanupNonceMap(): void {
  const now = Date.now();
  const map = gNonce.__orderNonceMap!;
  for (const [key, entry] of map) {
    if (now - entry.timestamp > NONCE_TTL_MS) {
      map.delete(key);
    }
  }
}

/**
 * POST /api/ancpi/order — create one or more CF extract orders.
 *
 * Body: { parcels: CfExtractCreateInput[], nonce?: string }
 *
 * If a `nonce` is provided and was already seen within the last 60 seconds,
 * the previous response is returned instead of creating duplicate orders.
 *
 * Returns: { orders: [{ id, nrCadastral, status }], deduplicated?: boolean }
 */
export async function POST(req: Request) {
  try {
    const creds = getEpayCredentials();
    if (!creds) {
      return NextResponse.json(
        { error: "Nu ești conectat la ePay ANCPI." },
        { status: 401 },
      );
    }

    const body = (await req.json()) as {
      parcels?: CfExtractCreateInput[];
      nonce?: string;
    };

    const parcels = body.parcels ?? [];
    if (parcels.length === 0) {
      return NextResponse.json(
        { error: "Nicio parcelă specificată." },
        { status: 400 },
      );
    }

    // ── Nonce idempotency check ──
    cleanupNonceMap();
    if (body.nonce) {
      const cached = gNonce.__orderNonceMap!.get(body.nonce);
      if (cached && Date.now() - cached.timestamp < NONCE_TTL_MS) {
        console.log(
          `[ancpi/order] Nonce dedup hit: "${body.nonce}" — returning cached response`,
        );
        return NextResponse.json({
          ...cached.response,
          deduplicated: true,
        });
      }
    }

    // Validate required fields
    for (const p of parcels) {
      if (!p.nrCadastral || p.judetIndex == null || p.uatId == null) {
        return NextResponse.json(
          {
            error: `Date lipsă pentru parcela ${p.nrCadastral ?? "?"}. Necesare: nrCadastral, judetIndex, uatId.`,
          },
          { status: 400 },
        );
      }
    }

    let responseBody: {
      orders: Array<{ id: string; nrCadastral: string; status: string }>;
    };

    if (parcels.length === 1) {
      const id = await enqueueOrder(parcels[0]!);
      responseBody = {
        orders: [
          {
            id,
            nrCadastral: parcels[0]!.nrCadastral,
            status: "queued",
          },
        ],
      };
    } else {
      const ids = await enqueueBatch(parcels);
      responseBody = {
        orders: ids.map((id, i) => ({
          id,
          nrCadastral: parcels[i]?.nrCadastral ?? "",
          status: "queued",
        })),
      };
    }

    // ── Cache response for nonce ──
    if (body.nonce) {
      gNonce.__orderNonceMap!.set(body.nonce, {
        timestamp: Date.now(),
        response: responseBody,
      });
    }

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