/**
 * SuperAdminConfigService.js
 *
 * Read-only status helper. The SuperAdmin UI no longer accepts API keys
 * — operators set them in `superadmin/server/.env` and restart the
 * process. This service is kept only for the `/supabase/config`
 * status probe (env vs missing) and the `validateSupabaseKey` helper
 * used by the SuperAdmin server's `getStatus()` to test connectivity.
 *
 * All write paths (`setSecret`, `deleteSecret`, disk persistence) have
 * been removed. Any legacy `superadmin/server/data/sa-config.json`
 * file is no longer consulted.
 */

const { createClient } = require('@supabase/supabase-js');

class SuperAdminConfigService {
  constructor() {
    // No disk or env-mutation side effects — read-only by design.
  }

  // Legacy read API kept for any callers that still probe by name.
  // Always returns undefined (env-only mode).
  getSecret(/* name */) {
    return undefined;
  }

  // Legacy has/list API: there is no longer any configured secret
  // store. Returns false / [] respectively.
  hasSecret(/* name */) {
    return false;
  }

  listConfigured() {
    return [];
  }

  async validateSupabaseKey(url, key) {
    if (!url || !key) {
      return { ok: false, error: 'Supabase URL and key are both required' };
    }
    let probeClient;
    try {
      probeClient = createClient(url, key, { auth: { persistSession: false } });
    } catch (err) {
      return { ok: false, error: `Failed to construct client: ${err.message}` };
    }

    const probe = async () => {
      const { error } = await probeClient.from('tenants').select('id').limit(1);
      if (!error) return null;
      const msg = String(error.message || error.code || '').toLowerCase();
      if (msg.includes('invalid api key') || msg.includes('invalid jwt') || msg.includes('401')) {
        return new Error('Supabase rejected the provided key (401). Verify SUPABASE_KEY (anon) in superadmin/server/.env.');
      }
      if (msg.includes('relation') && msg.includes('does not exist')) {
        return null;
      }
      return new Error(error.message || 'Probe query failed');
    };

    let timer;
    try {
      const timeoutPromise = new Promise((resolve) => {
        timer = setTimeout(() => resolve({ __timeout: true }), 5000);
      });
      const result = await Promise.race([probe(), timeoutPromise]);
      if (result && result.__timeout) {
        return { ok: false, error: 'Probe timed out after 5s' };
      }
      if (result instanceof Error) {
        return { ok: false, error: result.message };
      }
      return { ok: true };
    } catch (err) {
      return { ok: false, error: err.message };
    } finally {
      if (timer) clearTimeout(timer);
    }
  }
}

module.exports = new SuperAdminConfigService();
