import { NextResponse } from 'next/server';
import { getPayload } from 'payload';
import configPromise from '@payload-config';

export const dynamic = 'force-dynamic';

/**
 * Deep CMS Health Check
 * Validates that Payload CMS can actually query the database.
 * Used by post-deploy smoke tests to catch migration/schema issues.
 */
export async function GET() {
  const checks: Record<string, string> = {};

  try {
    const payload = await getPayload({ config: configPromise });
    checks.init = 'ok';

    // Verify each collection can be queried (catches missing locale tables, broken migrations)
    const collections = ['posts', 'products', 'pages', 'media'] as const;
    for (const collection of collections) {
      try {
        await payload.find({ collection, limit: 1, locale: 'en' });
        checks[collection] = 'ok';
      } catch (e: any) {
        checks[collection] = `error: ${e.message?.substring(0, 100)}`;
      }
    }

    const hasErrors = Object.values(checks).some(v => v.startsWith('error'));
    return NextResponse.json(
      { status: hasErrors ? 'degraded' : 'ok', checks },
      { status: hasErrors ? 503 : 200 },
    );
  } catch (e: any) {
    return NextResponse.json(
      { status: 'error', message: e.message?.substring(0, 200), checks },
      { status: 503 },
    );
  }
}
