import {
  Body,
  Controller,
  Get,
  Headers,
  HttpCode,
  Param,
  Post as HttpPost,
  Post,
  Query,
  Req,
  UseGuards,
} from '@nestjs/common';
import type { Request } from 'express';
import { AuthenticatedUser } from '../auth/auth.types';
import { WebhooksService } from './webhooks.service';
import { AuthGuard } from '../common/auth.guard';

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

  @Get('whatsapp')
  verify(
    @Query('hub.mode') mode?: string,
    @Query('hub.verify_token') token?: string,
    @Query('hub.challenge') challenge?: string,
  ) {
    return this.webhooksService.verifyChallenge(mode, token, challenge);
  }

  @HttpCode(200)
  @Post('whatsapp')
  receiveDefault(
    @Body() body: unknown,
    @Req() request: Request & { rawBody?: Buffer },
    @Headers() headers: Record<string, string | string[] | undefined>,
  ) {
    return this.webhooksService.receive('default', body, headers, request.rawBody);
  }

  @HttpCode(200)
  @Post('whatsapp/:provider')
  receiveByProvider(
    @Param('provider') provider: string,
    @Body() body: unknown,
    @Req() request: Request & { rawBody?: Buffer },
    @Headers() headers: Record<string, string | string[] | undefined>,
  ) {
    return this.webhooksService.receive(provider, body, headers, request.rawBody);
  }

  @UseGuards(AuthGuard)
  @Get('logs')
  logs(
    @Query('limit') limit?: string,
    @Query('provider') provider?: string,
    @Query('status') status?: string,
  ) {
    const parsedLimit = limit ? Number(limit) : 50;
    return this.webhooksService.findAll(
      Number.isFinite(parsedLimit) ? parsedLimit : 50,
      provider,
      status,
    );
  }

  @UseGuards(AuthGuard)
  @HttpPost('logs/:eventId/retry')
  retry(
    @Req() request: Request & { user: AuthenticatedUser },
    @Param('eventId') eventId: string,
  ) {
    return this.webhooksService.retryEvent(eventId, request.user, request.ip);
  }
}
