import { Controller, Post, Get, Body, Query, UseGuards, Req } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { JwtAuthGuard } from '@genex/common';
import { TelemetryService } from '../../../application/services/telemetry.service';
import { BatchEventsDto } from '../dto/batch-events.dto';
import { HeartbeatDto } from '../dto/heartbeat.dto';

@ApiTags('telemetry')
@Controller('telemetry')
export class TelemetryController {
  constructor(private readonly telemetryService: TelemetryService) {}

  @Post('events')
  @ApiOperation({ summary: 'Batch report telemetry events (no auth required)' })
  async batchEvents(@Body() body: BatchEventsDto) {
    const result = await this.telemetryService.recordEvents(body.events);
    return { code: 0, data: result };
  }

  @Post('heartbeat')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: 'Report heartbeat for online detection' })
  async heartbeat(@Req() req: any, @Body() body: HeartbeatDto) {
    await this.telemetryService.recordHeartbeat(req.user.sub, body.installId, body.appVersion);
    return { code: 0, data: { success: true } };
  }

  @Get('online-count')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: 'Get current online user count' })
  async getOnlineCount() {
    const result = await this.telemetryService.getOnlineCount();
    return { code: 0, data: result };
  }

  @Get('online-history')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: 'Get online user history trend' })
  async getOnlineHistory(
    @Query('startTime') startTime: string,
    @Query('endTime') endTime: string,
    @Query('interval') interval?: '1m' | '5m' | '1h',
  ) {
    const result = await this.telemetryService.getOnlineHistory(
      new Date(startTime),
      new Date(endTime),
      interval || '5m',
    );
    return { code: 0, data: result };
  }
}
