import {
  Controller,
  Get,
  Patch,
  Param,
  Body,
  NotFoundException,
} from '@nestjs/common';
import { AdapterRegistry } from '../../../infrastructure/adapters/adapter-registry';

@Controller('api/v1/comm/channels')
export class ChannelController {
  constructor(private readonly adapterRegistry: AdapterRegistry) {}

  /**
   * GET /api/v1/comm/channels
   * Returns a list of all registered channel types with availability status.
   */
  @Get()
  async listChannels() {
    const allAdapters = await this.adapterRegistry.getAvailableAdapters();
    const availableTypes = new Set(allAdapters.map((a) => a.channelType));

    // Build a list of all known channel types with their configuration status
    const channelTypes = [
      { type: 'websocket', label: 'WebSocket', description: 'Real-time web push notifications' },
      { type: 'sms', label: 'SMS', description: 'Short message service notifications' },
      { type: 'voice_call', label: 'Voice Call', description: 'Automated voice call alerts' },
      { type: 'voice_dialog', label: 'Voice Dialog', description: 'Interactive voice dialog via voice service' },
      { type: 'email', label: 'Email', description: 'Email notifications' },
      { type: 'telegram', label: 'Telegram', description: 'Telegram bot notifications' },
      { type: 'wechat', label: 'WeChat Work', description: 'WeChat Work (Enterprise WeChat) notifications' },
    ];

    return channelTypes.map((ch) => ({
      ...ch,
      available: availableTypes.has(ch.type as any),
      configured: availableTypes.has(ch.type as any),
    }));
  }

  /**
   * GET /api/v1/comm/channels/:type
   * Returns details for a specific channel type.
   */
  @Get(':type')
  async getChannel(@Param('type') type: string) {
    const adapter = this.adapterRegistry.getAdapter(type);
    if (!adapter) {
      throw new NotFoundException(`Channel type "${type}" not found`);
    }

    const available = await adapter.isAvailable();
    return {
      type: adapter.channelType,
      available,
      configured: available,
    };
  }

  /**
   * PATCH /api/v1/comm/channels/:type
   * Update channel configuration. For now returns the payload as-is.
   */
  @Patch(':type')
  async updateChannel(@Param('type') type: string, @Body() body: any) {
    const adapter = this.adapterRegistry.getAdapter(type);
    if (!adapter) {
      throw new NotFoundException(`Channel type "${type}" not found`);
    }

    return {
      type,
      updated: true,
      config: body,
    };
  }
}
