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

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

/** GET /api/ancpi/credits — current credit balance (live from ePay) */
export async function GET() {
  try {
    const status = getEpaySessionStatus();
    if (!status.connected) {
      return NextResponse.json({ credits: null, connected: false });
    }

    // Return cached if checked within last 60 seconds
    const lastChecked = status.creditsCheckedAt
      ? new Date(status.creditsCheckedAt).getTime()
      : 0;
    if (Date.now() - lastChecked < 60_000 && status.credits != null) {
      return NextResponse.json({
        credits: status.credits,
        connected: true,
        cached: true,
      });
    }

    // Fetch live from ePay
    const creds = getEpayCredentials();
    if (!creds) {
      return NextResponse.json({ credits: null, connected: false });
    }

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

    return NextResponse.json({ credits, connected: true, cached: false });
  } catch (error) {
    const message = error instanceof Error ? error.message : "Eroare";
    return NextResponse.json({ error: message, credits: null }, { status: 500 });
  }
}
