/**
 * Webhook 控制器
 * 
 * Webhook 订阅管理 API
 */

import {
  Controller,
  Get,
  Post,
  Patch,
  Delete,
  Body,
  Param,
  Query,
  UseGuards,
  Logger,
  HttpCode,
} from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiResponse,
  ApiBearerAuth,
  ApiHeader,
  ApiParam,
} from '@nestjs/swagger';
import { WebhookService } from '../services/webhook.service';
import { RegionGuard } from '../guards/region.guard';
import { Region, RegionRequired } from '../decorators/region.decorator';
import type { RegionId } from '../decorators/region.decorator';
import { RequirePermissions } from '@common/decorators/permissions.decorator';
import { CurrentUser } from '@common/decorators/current-user.decorator';
import { PermissionsGuard } from '@modules/organization/auth/guards/permissions.guard';
import { Auditable, Sensitive, Financial } from '@core/observability/audit/decorators/auditable.decorator';
import {
  CreateWebhookDto,
  UpdateWebhookDto,
  TestWebhookDto,
  QueryWebhookLogsDto,
} from '../dto/webhook.dto';

@ApiTags('Webhook 管理')
@ApiBearerAuth()
@ApiHeader({
  name: 'X-Region-Id',
  description: '区域标识（CN / US / ME）',
  required: true,
})
@Controller('form-management/webhooks')
@UseGuards(RegionGuard, PermissionsGuard)
@RegionRequired(true)
export class WebhookController {
  private readonly logger = new Logger(WebhookController.name);

  constructor(private readonly webhookService: WebhookService) {}

  @Post()
  @Auditable()
  @Sensitive()
  @ApiOperation({ summary: '创建 Webhook 订阅' })
  @ApiResponse({ status: 201, description: '创建成功' })
  @RequirePermissions('form:admin')
  async create(
    @Body() dto: CreateWebhookDto,
    @CurrentUser('userId') userId: string,
  ) {
    // v2.0: Webhook 不再按区域过滤，统一按 organizationId（null = 平台级）
    // 见 backend/prisma/schema/FORM_ORGANIZATION_ARCHITECTURE.md
    this.logger.log(`POST /webhooks - user: ${userId}`);
    return this.webhookService.create(dto, null, userId);
  }

  @Get()
  @ApiOperation({ summary: '获取 Webhook 列表' })
  @ApiResponse({ status: 200, description: '成功获取列表' })
  @RequirePermissions('form:admin')
  async findAll() {
    this.logger.log(`GET /webhooks`);
    return this.webhookService.findAll();
  }

  @Get(':id')
  @ApiOperation({ summary: '获取 Webhook 详情' })
  @ApiParam({ name: 'id', description: 'Webhook ID' })
  @ApiResponse({ status: 200, description: '成功获取详情' })
  @RequirePermissions('form:admin')
  async findOne(
    @Param('id') id: string,
  ) {
    this.logger.log(`GET /webhooks/${id}`);
    return this.webhookService.findOne(id);
  }

  @Patch(':id')
  @Auditable()
  @Sensitive()
  @ApiOperation({ summary: '更新 Webhook 配置' })
  @ApiParam({ name: 'id', description: 'Webhook ID' })
  @ApiResponse({ status: 200, description: '更新成功' })
  @RequirePermissions('form:admin')
  async update(
    @Param('id') id: string,
    @Body() dto: UpdateWebhookDto,
    @CurrentUser('userId') userId: string,
  ) {
    this.logger.log(`PATCH /webhooks/${id} - user: ${userId}`);
    return this.webhookService.update(id, dto, undefined, userId);
  }

  @Delete(':id')
  @Auditable()
  @Sensitive()
  @ApiOperation({ summary: '删除 Webhook' })
  @ApiParam({ name: 'id', description: 'Webhook ID' })
  @ApiResponse({ status: 200, description: '删除成功' })
  @RequirePermissions('form:admin')
  async remove(
    @Param('id') id: string,
  ) {
    this.logger.log(`DELETE /webhooks/${id}`);
    return this.webhookService.remove(id);
  }

  @Post(':id/test')
  @Auditable()
  @Sensitive()
  @HttpCode(200)
  @ApiOperation({ summary: '发送测试事件' })
  @ApiParam({ name: 'id', description: 'Webhook ID' })
  @ApiResponse({ status: 200, description: '测试完成' })
  @RequirePermissions('form:admin')
  async sendTestEvent(
    @Param('id') id: string,
    @Body() dto: TestWebhookDto,
  ) {
    this.logger.log(`POST /webhooks/${id}/test`);
    return this.webhookService.sendTestEvent(id, dto);
  }

  @Get(':id/logs')
  @ApiOperation({ summary: '查看投递日志' })
  @ApiParam({ name: 'id', description: 'Webhook ID' })
  @ApiResponse({ status: 200, description: '成功获取日志' })
  @RequirePermissions('form:admin')
  async findLogs(
    @Param('id') id: string,
    @Query() query: QueryWebhookLogsDto,
  ) {
    this.logger.log(`GET /webhooks/${id}/logs`);
    return this.webhookService.findLogs(id, query);
  }
}
