import { Controller, Get, Query } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiQuery, ApiBearerAuth } from '@nestjs/swagger';
import { PriceService } from '../../application/services/price.service';
import { MarketMakerService } from '../../application/services/market-maker.service';
import { TradingConfigRepository } from '../../infrastructure/persistence/repositories/trading-config.repository';
import { Public } from '../../shared/guards/jwt-auth.guard';

@ApiTags('Price')
@Controller('price')
export class PriceController {
  constructor(
    private readonly priceService: PriceService,
    private readonly marketMakerService: MarketMakerService,
    private readonly tradingConfigRepository: TradingConfigRepository,
  ) {}

  @Get('current')
  @Public()
  @ApiOperation({ summary: '获取当前价格信息' })
  async getCurrentPrice() {
    return this.priceService.getCurrentPrice();
  }

  @Get('latest')
  @Public()
  @ApiOperation({ summary: '获取最新价格快照' })
  async getLatestSnapshot() {
    const snapshot = await this.priceService.getLatestSnapshot();
    if (!snapshot) {
      return { message: 'No price snapshot available' };
    }
    return snapshot;
  }

  @Get('history')
  @Public()
  @ApiOperation({ summary: '获取价格历史' })
  @ApiQuery({ name: 'startTime', required: true, type: String, description: 'ISO datetime' })
  @ApiQuery({ name: 'endTime', required: true, type: String, description: 'ISO datetime' })
  @ApiQuery({ name: 'limit', required: false, type: Number })
  async getPriceHistory(
    @Query('startTime') startTime: string,
    @Query('endTime') endTime: string,
    @Query('limit') limit?: number,
  ) {
    return this.priceService.getPriceHistory(
      new Date(startTime),
      new Date(endTime),
      limit ?? 1440,
    );
  }

  @Get('klines')
  @Public()
  @ApiOperation({ summary: '获取K线数据（OHLC格式）' })
  @ApiQuery({
    name: 'period',
    required: false,
    type: String,
    description: 'K线周期: 1m, 5m, 15m, 30m, 1h, 4h, 1d, 1w, 1M, 1y',
    example: '1h',
  })
  @ApiQuery({ name: 'limit', required: false, type: Number, description: '返回数量，默认100' })
  @ApiQuery({
    name: 'before',
    required: false,
    type: String,
    description: '获取此时间之前的K线数据（ISO datetime），用于加载更多历史数据',
  })
  async getKlines(
    @Query('period') period: string = '1h',
    @Query('limit') limit: number = 100,
    @Query('before') before?: string,
  ) {
    const beforeTime = before ? new Date(before) : undefined;
    return this.priceService.getKlines(period, Math.min(limit, 500), beforeTime);
  }

  @Get('depth')
  @Public()
  @ApiOperation({ summary: '获取订单簿深度（买卖盘深度）' })
  @ApiQuery({ name: 'levels', required: false, type: Number, description: '深度档位数（默认10）' })
  async getDepth(@Query('levels') levels?: string) {
    // 检查深度功能是否启用
    const config = await this.tradingConfigRepository.getConfig();
    if (!config || !config.depthEnabled) {
      return {
        success: true,
        bids: [],
        asks: [],
        timestamp: Date.now(),
        message: '深度功能未启用',
      };
    }

    const depth = await this.marketMakerService.getDepth(levels ? parseInt(levels, 10) : 10);

    return {
      success: true,
      ...depth,
    };
  }
}
