import { NextResponse, type NextRequest } from 'next/server';
import { getFacets, isCumasConfigured, FACETS_CONST } from '@/lib/crm/cumas-client';
import { withAuth } from '@/core/auth';

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

const STUB_FACETS = {
  businessItsKsm: ['ITS', 'SITS', 'AITS', 'KSM', 'SKSM', 'AKSM', 'ASPA'],
  businessReseller: ['its', 'spa'],
  evbTyp: ['KZK', 'KZKA'],
  evbGesellschaft: ['WPRO', 'AXA', 'GEFION'],
  evbReseller: ['its', 'spa'],
  orderProducts: ['KZK', 'KZKA'],
  cachedAt: new Date().toISOString(),
};

function parsePages(raw: string | null, fallback: number): number {
  if (!raw) return fallback;
  const n = parseInt(raw, 10);
  if (isNaN(n)) return fallback;
  return Math.max(1, Math.min(50, n));
}

export const GET = withAuth(async (req: NextRequest, _ctx) => {
  const pages = parsePages(req.nextUrl.searchParams.get('pages'), FACETS_CONST.defaultPages);
  const refresh = req.nextUrl.searchParams.get('refresh') === '1';
  const sampleSize = {
    pages,
    recordsPerPage: FACETS_CONST.recordsPerPage,
    totalSampled: pages * FACETS_CONST.recordsPerPage,
  };

  try {
    if (!isCumasConfigured()) {
      return NextResponse.json({ ok: true, ...STUB_FACETS, meta: { source: 'stub' as const, sampleSize } });
    }
    const facets = await getFacets({ pages, refresh });
    return NextResponse.json({ ok: true, ...facets, meta: { source: 'cumas' as const, sampleSize } });
  } catch (err) {
    console.error('[/api/crm/facets] error:', err);
    return NextResponse.json({
      ok: true,
      ...STUB_FACETS,
      meta: { source: 'fallback' as const, sampleSize, error: err instanceof Error ? err.message : 'unknown' },
    });
  }
});
