import { pgQuery } from '@/lib/postgres/client';

/**
 * Checks whether the Setup Wizard must be shown.
 * Returns true if:
 *  - DB is unreachable (fresh install, no DB yet)
 *  - setup_complete flag is false/missing in settings
 *  - No admin employee exists
 */
export async function isSetupRequired(): Promise<boolean> {
  // Dev override: set SKIP_SETUP_CHECK=true to bypass wizard during development
  if (process.env.SKIP_SETUP_CHECK === 'true') return false;

  try {
    // Check setup_complete flag
    const result = await pgQuery<{ value: any }>(
      "SELECT value FROM settings WHERE key = 'setup_complete' LIMIT 1"
    );

    if (!result.rows.length) return true; // Table not seeded yet
    if (result.rows[0].value === true || result.rows[0].value === 'true') {
      // Double-check that at least one admin employee exists
      const empResult = await pgQuery<{ count: string }>(
        "SELECT COUNT(*) as count FROM employees WHERE role = 'admin' LIMIT 1"
      );
      const count = parseInt(empResult.rows[0]?.count ?? '0', 10);
      return count === 0;
    }

    return true;
  } catch {
    // DB not reachable or schema_migrations table missing → setup required
    return true;
  }
}

/**
 * Marks setup as complete in the settings table.
 */
export async function markSetupComplete(): Promise<void> {
  await pgQuery(
    `INSERT INTO settings (key, value, updated_at)
     VALUES ('setup_complete', 'true'::jsonb, NOW())
     ON CONFLICT (key) DO UPDATE SET value = 'true'::jsonb, updated_at = NOW()`
  );
}
