import { NextResponse, type NextRequest } from 'next/server';
import { inspectSchema, isCumasConfigured, SCHEMA_CONST, type ColumnInfo, type SchemaSnapshot } from '@/lib/crm/cumas-client';
import { withAuth } from '@/core/auth';

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

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));
}

/**
 * Stub-Schema für UI-Verifikation ohne Cumas-Credentials.
 * Reflektiert die wichtigsten Felder aus CumasBusinessRecord/EvbRecord/OrderRecord
 * mit synthetischen Top-Values + Counts, sodass das UI rendert wie im Live-Modus.
 */
const STUB_SCHEMA: SchemaSnapshot = {
  business: [
    { name: 'firma', kind: 'string', filledCount: 100, totalSampled: 100, distinctCount: 98, topValues: [] },
    { name: 'email', kind: 'string', filledCount: 92, totalSampled: 100, distinctCount: 92, topValues: [] },
    { name: 'its_ksm', kind: 'enum', filledCount: 100, totalSampled: 100, distinctCount: 5,
      topValues: [{ value: 'ITS', count: 62 }, { value: 'SITS', count: 18 }, { value: 'AITS', count: 8 }, { value: 'KSM', count: 9 }, { value: 'ASPA', count: 3 }] },
    { name: 'reseller', kind: 'enum', filledCount: 88, totalSampled: 100, distinctCount: 2,
      topValues: [{ value: 'its', count: 76 }, { value: 'spa', count: 12 }] },
    { name: 'plz', kind: 'string', filledCount: 95, totalSampled: 100, distinctCount: 78, topValues: [] },
    { name: 'ort', kind: 'string', filledCount: 95, totalSampled: 100, distinctCount: 67,
      topValues: [{ value: 'Berlin', count: 8 }, { value: 'München', count: 6 }, { value: 'Hamburg', count: 5 }] },
    { name: 'branche', kind: 'string', filledCount: 73, totalSampled: 100, distinctCount: 24, topValues: [] },
    { name: 'vorname_k1', kind: 'string', filledCount: 78, totalSampled: 100, distinctCount: 65, topValues: [] },
    { name: 'nachname_k1', kind: 'string', filledCount: 78, totalSampled: 100, distinctCount: 72, topValues: [] },
    { name: 'tel1', kind: 'string', filledCount: 81, totalSampled: 100, distinctCount: 81, topValues: [] },
    { name: 'website', kind: 'string', filledCount: 54, totalSampled: 100, distinctCount: 54, topValues: [] },
    { name: 'vshv_eigen', kind: 'boolean', filledCount: 100, totalSampled: 100, distinctCount: 2,
      topValues: [{ value: 'false', count: 76 }, { value: 'true', count: 24 }] },
    { name: 'vshv_fremd', kind: 'boolean', filledCount: 100, totalSampled: 100, distinctCount: 2,
      topValues: [{ value: 'false', count: 88 }, { value: 'true', count: 12 }] },
    { name: 'its_nr', kind: 'number', filledCount: 65, totalSampled: 100, distinctCount: 65, topValues: [], min: 1001, max: 99812 },
    { name: 'update_datetime', kind: 'date', filledCount: 100, totalSampled: 100, distinctCount: 100, topValues: [], min: '2023-01-15', max: '2026-04-28' },
  ],
  evb: [
    { name: 'email', kind: 'string', filledCount: 95, totalSampled: 100, distinctCount: 95, topValues: [] },
    { name: 'vorname', kind: 'string', filledCount: 100, totalSampled: 100, distinctCount: 88, topValues: [] },
    { name: 'nachname', kind: 'string', filledCount: 100, totalSampled: 100, distinctCount: 92, topValues: [] },
    { name: 'typ', kind: 'enum', filledCount: 100, totalSampled: 100, distinctCount: 2,
      topValues: [{ value: 'KZK', count: 84 }, { value: 'KZKA', count: 16 }] },
    { name: 'gesellschaft', kind: 'enum', filledCount: 100, totalSampled: 100, distinctCount: 3,
      topValues: [{ value: 'WPRO', count: 56 }, { value: 'AXA', count: 32 }, { value: 'GEFION', count: 12 }] },
  ],
  orders: [
    { name: 'email', kind: 'string', filledCount: 100, totalSampled: 100, distinctCount: 100, topValues: [] },
    { name: 'client_name', kind: 'string', filledCount: 100, totalSampled: 100, distinctCount: 96, topValues: [] },
    { name: 'product', kind: 'enum', filledCount: 100, totalSampled: 100, distinctCount: 2,
      topValues: [{ value: 'KZK', count: 78 }, { value: 'KZKA', count: 22 }] },
    { name: 'reg_datetime', kind: 'date', filledCount: 100, totalSampled: 100, distinctCount: 99, topValues: [], min: '2024-08-12', max: '2026-05-01' },
  ],
  cachedAt: new Date().toISOString(),
};

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

  try {
    if (!isCumasConfigured()) {
      return NextResponse.json({ ok: true, ...STUB_SCHEMA, meta: { source: 'stub' as const, sampleSize } });
    }
    const schema = await inspectSchema({ pages, refresh });
    return NextResponse.json({ ok: true, ...schema, meta: { source: 'cumas' as const, sampleSize } });
  } catch (err) {
    console.error('[/api/crm/schema] error:', err);
    // Defensive Fallback — Stub-Schema statt 500, damit UI nicht hart blockiert
    return NextResponse.json({
      ok: true,
      ...STUB_SCHEMA,
      meta: { source: 'fallback' as const, sampleSize, error: err instanceof Error ? err.message : 'unknown' },
    });
  }
});

export type { ColumnInfo, SchemaSnapshot };
