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

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

/**
 * POST /api/eterra/login
 * Legacy endpoint — kept for backward compat. Prefer /api/eterra/session.
 */
export async function POST(req: Request) {
  try {
    const body = (await req.json()) as { username?: string; password?: string };
    const username = (
      body.username ??
      process.env.ETERRA_USERNAME ??
      ""
    ).trim();
    const password = (
      body.password ??
      process.env.ETERRA_PASSWORD ??
      ""
    ).trim();
    if (!username || !password)
      return NextResponse.json(
        { error: "Credențiale eTerra lipsă" },
        { status: 400 },
      );

    await EterraClient.create(username, password);
    createSession(username, password);
    return NextResponse.json({ success: true });
  } catch (error) {
    const message = error instanceof Error ? error.message : "Eroare server";
    const status = message.toLowerCase().includes("login") ? 401 : 500;
    return NextResponse.json({ error: message }, { status });
  }
}
