import { Controller, Post, Get, Body, Query, UseGuards, Req } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { JwtAuthGuard } from '../../../shared/guards/jwt-auth.guard';
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) {}

  /**
   * 遥测客户端配置接口（无需认证）
   *
   * Flutter TelemetryConfig.syncFromRemote() 每小时调用一次此接口，
   * 获取服务端下发的遥测开关、采样率、心跳配置等。
   *
   * 所有字段均有环境变量覆盖，默认值为生产安全值（全量采集、10% 采样）。
   *
   * 响应字段说明：
   *   global_enabled          — 遥测总开关，false 时客户端停止所有上报
   *   error_report_enabled    — 错误/崩溃上报开关（建议始终 true）
   *   performance_enabled     — 性能监控开关
   *   user_action_enabled     — 用户行为事件开关
   *   page_view_enabled       — 页面访问事件开关
   *   session_enabled         — 会话事件开关（DAU 依赖此项）
   *   sampling_rate           — 采样率 0~1（仅影响 userAction/pageView/performance 类型）
   *   disabled_events         — 事件黑名单（精确匹配 eventName）
   *   version                 — 配置版本，客户端用于判断是否需要刷新本地缓存
   *   presence_config         — 心跳子配置
   *     heartbeat_interval_seconds — 心跳间隔秒数（默认 60）
   *     requires_auth              — true: 未登录用户不发心跳
   *     presence_enabled           — 心跳总开关
   */
  @Get('config')
  @ApiOperation({
    summary: '获取遥测客户端配置（公开接口，无需认证）',
    description: 'Flutter TelemetryConfig.syncFromRemote() 调用，每小时同步一次',
  })
  getConfig() {
    return {
      code: 0,
      data: {
        global_enabled: process.env.TELEMETRY_GLOBAL_ENABLED !== 'false',
        error_report_enabled: process.env.TELEMETRY_ERROR_ENABLED !== 'false',
        performance_enabled: process.env.TELEMETRY_PERFORMANCE_ENABLED !== 'false',
        user_action_enabled: process.env.TELEMETRY_USER_ACTION_ENABLED !== 'false',
        page_view_enabled: process.env.TELEMETRY_PAGE_VIEW_ENABLED !== 'false',
        session_enabled: process.env.TELEMETRY_SESSION_ENABLED !== 'false',
        sampling_rate: parseFloat(process.env.TELEMETRY_SAMPLING_RATE || '0.1'),
        disabled_events: (process.env.TELEMETRY_DISABLED_EVENTS || '')
          .split(',')
          .map((s) => s.trim())
          .filter(Boolean),
        version: process.env.TELEMETRY_CONFIG_VERSION || '1.0.0',
        presence_config: {
          heartbeat_interval_seconds: parseInt(
            process.env.TELEMETRY_HEARTBEAT_INTERVAL || '60',
            10,
          ),
          requires_auth: process.env.TELEMETRY_HEARTBEAT_REQUIRES_AUTH !== 'false',
          presence_enabled: process.env.TELEMETRY_PRESENCE_ENABLED !== 'false',
        },
      },
    };
  }

  @Post('events')
  @ApiOperation({ summary: '批量上报遥测事件（无需认证）' })
  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: '上报心跳（维持在线状态）' })
  async heartbeat(@Req() req: any, @Body() body: HeartbeatDto) {
    // JwtStrategy.validate() 返回 { id, role, kycLevel }，故取 req.user.id
    await this.telemetryService.recordHeartbeat(req.user.id, body.installId, body.appVersion);
    return { code: 0, data: { ok: true, serverTs: Math.floor(Date.now() / 1000) } };
  }

  @Get('online-count')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取当前在线人数' })
  async getOnlineCount() {
    const result = await this.telemetryService.getOnlineCount();
    return { code: 0, data: result };
  }

  @Get('online-history')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取在线人数历史趋势' })
  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 };
  }
}
