import { Body, Controller, Get, HttpStatus, Inject, Post, Res } from '@nestjs/common';
import { ApiBody, ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import type { Response } from 'express';
import { Public } from '../auth/Public';
import { AnalyticsService } from './AnalyticsService';
import { GetAnalyticsMetricsOutputDTO } from './dtos/GetAnalyticsMetricsOutputDTO';
import { GetDashboardDataOutputDTO } from './dtos/GetDashboardDataOutputDTO';
import { RecordEngagementInputDTO } from './dtos/RecordEngagementInputDTO';
import { RecordEngagementOutputDTO } from './dtos/RecordEngagementOutputDTO';
import { RecordPageViewInputDTO } from './dtos/RecordPageViewInputDTO';
import { RecordPageViewOutputDTO } from './dtos/RecordPageViewOutputDTO';

type RecordPageViewInput = RecordPageViewInputDTO;
type RecordEngagementInput = RecordEngagementInputDTO;

@ApiTags('analytics')
@Controller('analytics')
export class AnalyticsController {
  constructor(
    @Inject(AnalyticsService) private readonly analyticsService: AnalyticsService,
  ) {}

  @Public()
  @Post('page-view')
  @ApiOperation({ summary: 'Record a page view' })
  @ApiBody({ type: RecordPageViewInputDTO })
  @ApiResponse({ status: 201, description: 'Page view recorded', type: RecordPageViewOutputDTO })
  async recordPageView(
    @Body() input: RecordPageViewInput,
    @Res() res: Response,
  ): Promise<void> {
    const dto = await this.analyticsService.recordPageView(input);
    res.status(HttpStatus.CREATED).json(dto);
  }

  @Public()
  @Post('engagement')
  @ApiOperation({ summary: 'Record an engagement event' })
  @ApiBody({ type: RecordEngagementInputDTO })
  @ApiResponse({ status: 201, description: 'Engagement recorded', type: RecordEngagementOutputDTO })
  async recordEngagement(
    @Body() input: RecordEngagementInput,
    @Res() res: Response,
  ): Promise<void> {
    const dto = await this.analyticsService.recordEngagement(input);
    res.status(HttpStatus.CREATED).json(dto);
  }

  // Dashboard/metrics are internal and should not be publicly exposed.
  @Get('dashboard')
  @ApiOperation({ summary: 'Get analytics dashboard data' })
  @ApiResponse({ status: 200, description: 'Dashboard data', type: GetDashboardDataOutputDTO })
  async getDashboardData(): Promise<GetDashboardDataOutputDTO> {
    return this.analyticsService.getDashboardData();
  }

  @Get('metrics')
  @ApiOperation({ summary: 'Get analytics metrics' })
  @ApiResponse({ status: 200, description: 'Analytics metrics', type: GetAnalyticsMetricsOutputDTO })
  @ApiResponse({ status: 401, description: 'Unauthorized' })
  async getAnalyticsMetrics(): Promise<GetAnalyticsMetricsOutputDTO> {
    return this.analyticsService.getAnalyticsMetrics();
  }
}
