import { NextResponse } from 'next/server';

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

const REQUIRED_ENV = ['PLATFORM_API_URL', 'JWT_SECRET', 'DEFAULT_PRODUCT_ID'];
const PLATFORM_HEALTH_TIMEOUT_MS = 2_000;

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 checkPlatformService(): Promise<Check> {
  const baseUrl = process.env.PLATFORM_API_URL;
  if (!baseUrl) {
    return { name: 'platform-service', status: 'fail', message: 'PLATFORM_API_URL missing' };
  }

  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), PLATFORM_HEALTH_TIMEOUT_MS);
  try {
    const res = await fetch(new URL('/health', baseUrl).toString(), {
      cache: 'no-store',
      signal: controller.signal,
    });
    if (!res.ok) {
      return { name: 'platform-service', status: 'fail', message: `HTTP ${res.status}` };
    }
    return { name: 'platform-service', status: 'pass', message: 'healthy' };
  } catch (err) {
    return {
      name: 'platform-service',
      status: 'fail',
      message: err instanceof Error ? err.message : 'health check failed',
    };
  } finally {
    clearTimeout(timeout);
  }
}

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

  const envCheck = checkEnvVars();
  checks.push(envCheck);
  if (envCheck.status === 'pass') {
    checks.push(await checkPlatformService());
  }

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

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