import { NextResponse } from "next/server";
import { syncLayer } from "@/modules/parcel-sync/services/sync-service";
import { getSessionCredentials } from "@/modules/parcel-sync/services/session-store";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export const maxDuration = 300; // 5 minute timeout for long syncs

type Body = {
  username?: string;
  password?: string;
  siruta?: string | number;
  layerId?: string;
  uatName?: string;
  jobId?: string;
  forceFullSync?: boolean;
};

export async function POST(req: Request) {
  try {
    const body = (await req.json()) as Body;
    const session = getSessionCredentials();
    const username = String(
      body.username || session?.username || process.env.ETERRA_USERNAME || "",
    ).trim();
    const password = String(
      body.password || session?.password || process.env.ETERRA_PASSWORD || "",
    ).trim();
    const siruta = String(body.siruta ?? "").trim();
    const layerId = String(body.layerId ?? "TERENURI_ACTIVE").trim();

    if (!username || !password)
      return NextResponse.json({ error: "Credențiale lipsă" }, { status: 400 });
    if (!/^\d+$/.test(siruta))
      return NextResponse.json({ error: "SIRUTA invalid" }, { status: 400 });

    const result = await syncLayer(username, password, siruta, layerId, {
      uatName: body.uatName,
      jobId: body.jobId,
      forceFullSync: body.forceFullSync,
    });

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