import {
  Controller,
  Get,
  Post,
  Body,
  Query,
  HttpCode,
  Logger,
  Res,
} from '@nestjs/common';
import { Response } from 'express';
import { ApiResponseLogService } from './api-response-log.service';
import { Public } from '../auth/public.decorator';
import { ApiTags, ApiOperation } from '@nestjs/swagger';

@ApiTags('intake')
@Controller('intake')
export class IntakeController {
  private readonly logger = new Logger(IntakeController.name);

  constructor(private readonly logService: ApiResponseLogService) { }

  /**
   * GET /jobvumi/api/intake
   * Handles:
   *  1. WhatsApp Cloud API verification handshake (hub.mode, hub.verify_token, hub.challenge)
   *  2. Any generic GET ping → returns plain "OK"
   */
  @Public()
  @Get()
  @HttpCode(200)
  handleGet(@Query() query: any, @Res() res: Response) {
    const mode = query['hub.mode'];
    const token = query['hub.verify_token'];
    const challenge = query['hub.challenge'];

    // WhatsApp verification handshake
    if (mode === 'subscribe' && token === process.env.WHATSAPP_VERIFY_TOKEN) {
      this.logger.log('[Intake] WhatsApp verification handshake successful');
      return res.status(200).send(challenge);
    }

    // Generic ping / health-check
    return res.status(200).send('OK');
  }

  /**
   * POST /jobvumi/api/intake
   * Accepts any JSON payload, determines source, saves to DB.
   * Always returns HTTP 200 — even on internal failure.
   */
  @Public()
  @Post()
  @HttpCode(200)
  @ApiOperation({ summary: 'Generic intake endpoint — stores raw JSON payload' })
  async handlePost(@Body() body: any, @Query('source') querySource?: string) {
    // Simply take source from the URL (?source=sms) or the body, otherwise null
    const source = querySource || body?.source || null;
    const message = body;

    try {
      const saved = await this.logService.store({ source, message });
      return {
        id: saved.id,
        source: saved.source,
        message: saved.message,
        created_at: saved.created_at,
      };
    } catch (err) {
      this.logger.error('[Intake] Failed to store payload', err?.stack ?? err);
      // Still return 200 so senders (WhatsApp etc.) never retry
      return {
        id: null,
        source,
        message,
        created_at: null,
        error: 'failed to store, logged internally',
      };
    }
  }

  /**
   * GET /jobvumi/api/intake/logs
   * Fetch paginated list of logged responses.
   */
  @Public()
  @Get('logs')
  @ApiOperation({ summary: 'Get paginated list of intake logs' })
  async getLogs(
    @Query('page') page: string = '1',
    @Query('limit') limit: string = '20',
  ) {
    return await this.logService.findAll(Number(page), Number(limit));
  }
}
