import { Controller, Get, Post, Patch, Delete, Body, Param, UseGuards } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../../auth/guards/roles.guard';
import { ModuleGuard } from '../../../common/guards/module.guard';
import { Roles, UserRole } from '../../../common/decorators/roles.decorator';
import { RequireModule } from '../../../common/decorators/require-module.decorator';
import { BotWebhookService, TG_BOT_EVENTS } from '../services/bot-webhook.service';
import { CreateBotWebhookDto, UpdateBotWebhookDto } from '../dto/bot-webhook.dto';

@ApiTags('Telegram Bot — Webhooks')
@ApiBearerAuth()
@Controller('telegram-bot/bots/:botId/webhooks')
@UseGuards(JwtAuthGuard, RolesGuard, ModuleGuard)
@RequireModule('telegram_bot')
@Roles(UserRole.CLUB_ADMIN, UserRole.SUPER_ADMIN)
export class BotWebhookController {
  constructor(private readonly webhooks: BotWebhookService) {}

  @Post()
  @ApiOperation({ summary: 'Create webhook subscription' })
  async create(@Param('botId') botId: string, @Body() dto: CreateBotWebhookDto) {
    // clubId is extracted from bot (botId is already scoped)
    const bot = await this.webhooks['prisma'].tgBot.findUnique({ where: { id: botId } });
    return this.webhooks.create(bot?.clubId ?? '', botId, dto);
  }

  @Get()
  @ApiOperation({ summary: 'List webhook subscriptions' })
  async findAll(@Param('botId') botId: string) {
    return this.webhooks.findAll(botId);
  }

  @Get('events')
  @ApiOperation({ summary: 'List available event types' })
  listEvents() {
    return { events: TG_BOT_EVENTS };
  }

  @Patch(':id')
  @ApiOperation({ summary: 'Update webhook subscription' })
  async update(
    @Param('botId') botId: string,
    @Param('id') id: string,
    @Body() dto: UpdateBotWebhookDto,
  ) {
    return this.webhooks.update(id, botId, dto);
  }

  @Delete(':id')
  @ApiOperation({ summary: 'Delete webhook subscription' })
  async remove(@Param('botId') botId: string, @Param('id') id: string) {
    return this.webhooks.remove(id, botId);
  }

  @Post(':id/test')
  @ApiOperation({ summary: 'Send test webhook' })
  async test(@Param('botId') botId: string, @Param('id') id: string) {
    return this.webhooks.test(id, botId);
  }
}
