// Quick health check - verifies env vars and DB connectivity.
// Run with: pnpm tsx scripts/preflight.ts

import { PrismaClient } from '@prisma/client';
import * as dotenv from 'dotenv';
import * as path from 'path';

dotenv.config({ path: path.resolve(__dirname, '../.env') });

const REQUIRED_ENV = [
  'DATABASE_URL',
  'JWT_SECRET',
  'API_PORT',
  'WEB_ORIGIN',
];

const RECOMMENDED_ENV = [
  'GOOGLE_MAPS_BACKEND_KEY',
  'NEXT_PUBLIC_GOOGLE_MAPS_FRONTEND_KEY',
  'REDIS_URL',
  'CRON_SECRET',
];

function checkEnv(): { ok: boolean; missing: string[]; warnings: string[] } {
  const missing: string[] = [];
  const warnings: string[] = [];

  for (const key of REQUIRED_ENV) {
    if (!process.env[key]) missing.push(key);
  }
  for (const key of RECOMMENDED_ENV) {
    if (!process.env[key]) warnings.push(key);
  }

  if (process.env.JWT_SECRET && process.env.JWT_SECRET.length < 32) {
    warnings.push('JWT_SECRET is shorter than 32 chars - regenerate with `openssl rand -hex 64`');
  }

  return { ok: missing.length === 0, missing, warnings };
}

async function checkDb(): Promise<{ ok: boolean; error?: string }> {
  const prisma = new PrismaClient();
  try {
    await prisma.$queryRaw`SELECT 1`;
    return { ok: true };
  } catch (e) {
    return { ok: false, error: e instanceof Error ? e.message : String(e) };
  } finally {
    await prisma.$disconnect();
  }
}

async function main() {
  console.log('🚦 Vihar Sewa preflight check\n');

  const env = checkEnv();
  if (env.ok) {
    console.log('✓ Required env vars present');
  } else {
    console.error('✗ Missing required env vars:', env.missing.join(', '));
  }
  if (env.warnings.length) {
    console.warn('⚠ Warnings:');
    env.warnings.forEach((w) => console.warn(`   - ${w}`));
  }

  const db = await checkDb();
  if (db.ok) {
    console.log('✓ Database reachable');
  } else {
    console.error('✗ Database NOT reachable:', db.error);
  }

  if (!env.ok || !db.ok) {
    process.exit(1);
  }
  console.log('\n✅ Preflight passed\n');
}

main();
