import { NextRequest, NextResponse } from 'next/server';
import {
  isCoolifyInfraOperational,
  runCoolifyInfraHealthProbe,
} from '@/lib/server/infra-coolify-health';

/**
 * Authenticated infrastructure probe for Coolify API + SSH→Docker.
 *
 * Configure on deploy:
 *   INFRA_HEALTH_SECRET   — required; pass as Authorization: Bearer <secret>
 *
 * Use from Cron / UptimeRobot / Better Stack:
 *   curl -sf -H "Authorization: Bearer $INFRA_HEALTH_SECRET" \
 *     https://<your-app>/api/internal/infra-health
 *
 * Returns 200 only when Coolify API and SSH+docker on the host are OK.
 */
export async function GET(req: NextRequest) {
  const secret = process.env.INFRA_HEALTH_SECRET?.trim();
  if (!secret) {
    return NextResponse.json(
      {
        ok: false,
        error:
          'INFRA_HEALTH_SECRET is not set — configure it on vibn-frontend to enable this probe.',
      },
      { status: 503 },
    );
  }

  const auth = req.headers.get('authorization');
  const bearer =
    auth?.startsWith('Bearer ') ? auth.slice(7).trim() : '';
  const headerSecret = req.headers.get('x-vibn-infra-secret')?.trim() ?? '';
  const token = bearer || headerSecret;

  if (token !== secret) {
    return NextResponse.json({ ok: false, error: 'Unauthorized' }, { status: 401 });
  }

  try {
    const report = await runCoolifyInfraHealthProbe();
    const ok = isCoolifyInfraOperational(report);
    return NextResponse.json({ ok, report }, { status: ok ? 200 : 503 });
  } catch (e) {
    const message = e instanceof Error ? e.message : String(e);
    return NextResponse.json({ ok: false, error: message }, { status: 503 });
  }
}
