import { strict as assert } from 'node:assert';
import { describe, it } from 'node:test';
import { Hono } from 'hono';
import type { Principal } from '../src/lib/auth';
import { AuthError } from '../src/lib/auth';
import { loadConfig } from '../src/lib/config';
import type { ApiEnv } from '../src/lib/mutation';
import {
  createIntegrationSettingsRoutes,
  integrationReadiness,
} from '../src/routes/integration-settings';

const config = loadConfig({
  DATABASE_URL: 'postgres://pig:pig@localhost:5432/pig',
  NODE_ENV: 'test',
  SLACK_BOT_TOKEN: 'xoxb-secret-value',
  SLACK_SIGNING_SECRET: 'slack-signing-secret',
  BUZZ_RELAY_URL: 'https://buzz.example.com',
  BUZZ_PRIVATE_KEY: 'buzz-private-secret',
  BUZZ_AUTH_TAG: '["auth","owner","kind=9","secret-signature"]',
});

function principal(isPlatformAdmin: boolean): Principal {
  return {
    userId: '00000000-0000-4000-8000-000000000001',
    email: 'admin@example.com',
    name: 'Admin',
    isPlatformAdmin,
    teams: [],
    via: 'jwt',
    scopes: ['read', 'write'],
  };
}

describe('integration readiness', () => {
  it('reports readiness without serialising any credential material', () => {
    const body = JSON.stringify(integrationReadiness(config));
    assert.deepEqual(JSON.parse(body), {
      slack: {
        source: 'environment',
        configured: true,
        deliveryReady: true,
        commandsReady: true,
      },
      buzz: {
        source: 'environment',
        configured: true,
        deliveryReady: true,
        relayUrl: 'https://buzz.example.com',
        workspaceId: 'buzz.example.com',
      },
    });
    for (const secret of [
      config.SLACK_BOT_TOKEN,
      config.SLACK_SIGNING_SECRET,
      config.BUZZ_PRIVATE_KEY,
      config.BUZZ_AUTH_TAG,
    ]) {
      assert.ok(secret);
      assert.equal(body.includes(secret), false);
    }
  });

  it('authorizes before returning readiness metadata', async () => {
    const app = new Hono<ApiEnv>();
    app.use('*', async (c, next) => {
      c.set('principal', principal(false));
      await next();
    });
    app.route('/', createIntegrationSettingsRoutes(config));
    app.onError((error, c) => {
      if (error instanceof AuthError) return c.json({ code: error.code }, error.status);
      throw error;
    });

    const response = await app.request('/api/admin/integrations');
    assert.equal(response.status, 403);
    assert.deepEqual(await response.json(), { code: 'insufficient_permission' });
  });
});
