import { Hono } from 'hono';
import type { Config } from '../lib/config';
import { requireCapability } from '../lib/auth';
import type { ApiEnv } from '../lib/mutation';
import { normaliseBuzzRelayUrl } from '../services/buzz';

export interface IntegrationReadiness {
  slack: {
    source: 'environment';
    configured: boolean;
    deliveryReady: boolean;
    commandsReady: boolean;
  };
  buzz: {
    source: 'environment';
    configured: boolean;
    deliveryReady: boolean;
    relayUrl: string | null;
    workspaceId: string | null;
  };
}

export function integrationReadiness(config: Config): IntegrationReadiness {
  const buzzRelayUrl = config.BUZZ_RELAY_URL
    ? normaliseBuzzRelayUrl(config.BUZZ_RELAY_URL)
    : null;
  const slackDeliveryReady = Boolean(config.SLACK_BOT_TOKEN);
  const slackCommandsReady = Boolean(config.SLACK_SIGNING_SECRET);
  const buzzReady = Boolean(buzzRelayUrl && config.BUZZ_PRIVATE_KEY);

  return {
    slack: {
      source: 'environment',
      configured: slackDeliveryReady && slackCommandsReady,
      deliveryReady: slackDeliveryReady,
      commandsReady: slackCommandsReady,
    },
    buzz: {
      source: 'environment',
      configured: buzzReady,
      deliveryReady: buzzReady,
      relayUrl: buzzRelayUrl,
      workspaceId: buzzRelayUrl ? new URL(buzzRelayUrl).host : null,
    },
  };
}

export function createIntegrationSettingsRoutes(config: Config): Hono<ApiEnv> {
  const app = new Hono<ApiEnv>();
  app.get('/api/admin/integrations', (c) => {
    requireCapability(c.get('principal'), 'settings:admin');
    return c.json(integrationReadiness(config));
  });
  return app;
}
