import {
  Controller,
  Get,
  Post,
  Patch,
  Delete,
  Body,
  Param,
} from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { WebhooksService } from './webhooks.service';
import { CreateWebhookDto } from './dto/create-webhook.dto';
import { UpdateWebhookDto } from './dto/update-webhook.dto';
import { CurrentTenant } from '../../common/decorators/current-tenant.decorator';
import { RequirePermission } from '../../common/decorators/require-permission.decorator';

@ApiTags('webhooks')
@ApiBearerAuth()
@Controller('webhooks')
export class WebhooksController {
  constructor(private readonly webhooksService: WebhooksService) {}

  @Post()
  @RequirePermission('webhooks.manage')
  @ApiOperation({
    summary: 'Create a webhook',
    description:
      'Registers a new outbound webhook for this license. A signing secret is auto-generated if not provided.',
  })
  @ApiResponse({ status: 201, description: 'Webhook created.' })
  async create(
    @CurrentTenant() licenseId: string,
    @Body() dto: CreateWebhookDto,
  ) {
    return this.webhooksService.create(licenseId, dto);
  }

  @Get()
  @RequirePermission('webhooks.view')
  @ApiOperation({ summary: 'List webhooks', description: 'Returns all webhooks for this license.' })
  @ApiResponse({ status: 200, description: 'Webhook list.' })
  async list(@CurrentTenant() licenseId: string) {
    return this.webhooksService.list(licenseId);
  }

  @Patch(':id')
  @RequirePermission('webhooks.manage')
  @ApiOperation({ summary: 'Update a webhook', description: 'Update name, URL, event subscriptions, or active state.' })
  @ApiResponse({ status: 200, description: 'Webhook updated.' })
  @ApiResponse({ status: 404, description: 'Webhook not found in this license.' })
  async update(
    @CurrentTenant() licenseId: string,
    @Param('id') id: string,
    @Body() dto: UpdateWebhookDto,
  ) {
    return this.webhooksService.update(licenseId, id, dto);
  }

  @Delete(':id')
  @RequirePermission('webhooks.manage')
  @ApiOperation({ summary: 'Delete a webhook' })
  @ApiResponse({ status: 200, description: 'Webhook deleted.' })
  @ApiResponse({ status: 404, description: 'Webhook not found in this license.' })
  async remove(
    @CurrentTenant() licenseId: string,
    @Param('id') id: string,
  ) {
    return this.webhooksService.remove(licenseId, id);
  }
}
