import assert from 'node:assert/strict';
import { pathToFileURL } from 'node:url';

const repoRoot = process.cwd();
const envModule = await import(pathToFileURL(`${repoRoot}/apps/taro/src/env.ts`).href);

envModule.applyRuntimeConfig({
  portal: 'tenant-admin',
  apiBaseUrl: 'https://api.gongxue100.com///',
  supabaseUrl: 'https://auth.gongxue100.com///',
  supabasePublishableKey: 'sb_publishable_public_key',
  tenantCode: 'tenant-a',
});

assert.equal(envModule.appEnv.portal, 'tenant-admin');
assert.equal(envModule.appEnv.apiBaseUrl, 'https://api.gongxue100.com');
assert.equal(envModule.appEnv.supabaseUrl, 'https://auth.gongxue100.com');
assert.equal(envModule.appEnv.supabasePublishableKey, 'sb_publishable_public_key');
assert.equal(envModule.appEnv.tenantCode, 'tenant-a');

envModule.applyRuntimeConfig({
  TARO_APP_PORTAL: 'platform-admin',
  TARO_APP_API_BASE_URL: 'https://api2.gongxue100.com',
});

assert.equal(envModule.appEnv.portal, 'platform-admin');
assert.equal(envModule.appEnv.apiBaseUrl, 'https://api2.gongxue100.com');

envModule.applyRuntimeConfig({
  portal: 'invalid-portal',
  apiBaseUrl: '',
});

assert.equal(envModule.appEnv.portal, 'platform-admin');
assert.equal(envModule.appEnv.apiBaseUrl, 'https://api2.gongxue100.com');

assert.throws(
  () => envModule.applyRuntimeConfig({
    apiBaseUrl: 'https://api.gongxue100.com',
    SUPABASE_SERVICE_ROLE_KEY: 'must-not-ship-to-browser',
  }),
  /Forbidden secret key in runtime config: SUPABASE_SERVICE_ROLE_KEY/,
);

assert.throws(
  () => envModule.applyRuntimeConfig({
    apiBaseUrl: 'https://api.gongxue100.com',
    unexpectedFeatureFlag: 'unsafe-drift',
  }),
  /Unknown key in runtime config: unexpectedFeatureFlag/,
);

console.log('[PASS] Taro runtime config guardrails');
