import { NextResponse } from 'next/server';
import { isDatastoreHealthy } from '@/lib/datastore';

interface Check {
  name: string;
  status: 'pass' | 'fail';
  message?: string;
  latencyMs?: number;
}

const REQUIRED_ENV = [
  'COSMOS_ENDPOINT',
  'COSMOS_KEY',
  'COSMOS_DATABASE',
  'JWT_SECRET',
  'STRIPE_SECRET_KEY',
  'SEED_SECRET',
];

function checkEnvVars(): Check {
  const missing = REQUIRED_ENV.filter(key => !process.env[key]);
  if (missing.length > 0) {
    return { name: 'env', status: 'fail', message: `Missing: ${missing.join(', ')}` };
  }
  return { name: 'env', status: 'pass', message: `${REQUIRED_ENV.length} required vars set` };
}

async function checkDatastore(): Promise<Check> {
  const start = Date.now();
  try {
    const healthy = await isDatastoreHealthy();
    return {
      name: 'datastore',
      status: healthy ? 'pass' : 'fail',
      latencyMs: Date.now() - start,
    };
  } catch (err) {
    return {
      name: 'datastore',
      status: 'fail',
      message: err instanceof Error ? err.message : String(err),
      latencyMs: Date.now() - start,
    };
  }
}

export async function GET() {
  const checks: Check[] = [];

  checks.push(checkEnvVars());
  checks.push(await checkDatastore());

  const overall = checks.every(c => c.status === 'pass') ? 'ok' : 'degraded';

  return NextResponse.json(
    {
      status: overall,
      service: 'admin-dashboard',
      timestamp: new Date().toISOString(),
      checks,
    },
    { status: overall === 'ok' ? 200 : 503 }
  );
}
