import { NextResponse } from "next/server";
import { EpayClient } from "@/modules/parcel-sync/services/epay-client";
import {
  createEpaySession,
  destroyEpaySession,
  getEpaySessionStatus,
} from "@/modules/parcel-sync/services/epay-session-store";

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

/** GET /api/ancpi/session — status + credits */
export async function GET() {
  return NextResponse.json(getEpaySessionStatus());
}

/** POST /api/ancpi/session — connect or disconnect */
export async function POST(req: Request) {
  try {
    const body = (await req.json()) as {
      action?: string;
      username?: string;
      password?: string;
    };

    if (body.action === "disconnect") {
      destroyEpaySession();
      return NextResponse.json({ success: true, disconnected: true });
    }

    // Connect
    const username = (
      body.username ?? process.env.ANCPI_USERNAME ?? ""
    ).trim();
    const password = (
      body.password ?? process.env.ANCPI_PASSWORD ?? ""
    ).trim();

    if (!username || !password) {
      return NextResponse.json(
        { error: "Credențiale ANCPI lipsă" },
        { status: 400 },
      );
    }

    const client = await EpayClient.create(username, password);
    const credits = await client.getCredits();
    createEpaySession(username, password, credits);

    return NextResponse.json({ success: true, credits });
  } 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 });
  }
}
