import {
  Controller,
  Get,
  Post,
  Query,
  HttpCode,
  HttpStatus,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiQuery } from '@nestjs/swagger';
import { C2cBotService } from '../../application/services/c2c-bot.service';
import { C2cBotScheduler } from '../../application/schedulers/c2c-bot.scheduler';
import { C2cOrderRepository } from '../../infrastructure/persistence/repositories/c2c-order.repository';
import { BlockchainClient } from '../../infrastructure/blockchain/blockchain.client';
import { RedisService } from '../../infrastructure/redis/redis.service';
import { Public } from '../../shared/guards/jwt-auth.guard';

@ApiTags('C2C Bot Admin')
@Controller('admin/c2c-bot')
export class C2cBotController {
  constructor(
    private readonly c2cBotService: C2cBotService,
    private readonly c2cOrderRepository: C2cOrderRepository,
    private readonly blockchainClient: BlockchainClient,
    private readonly redis: RedisService,
  ) {}

  @Get('status')
  @Public()
  @ApiOperation({ summary: '获取 C2C Bot 状态' })
  async getStatus() {
    const [enabled, blockchainAvailable, balance, status, stats] = await Promise.all([
      this.redis.get(C2cBotScheduler.ENABLED_KEY).then((v) => v === 'true'),
      this.c2cBotService.isAvailable(),
      this.c2cBotService.getHotWalletBalance(),
      this.blockchainClient.getStatus(),
      this.c2cOrderRepository.getBotStats(),
    ]);

    return {
      success: true,
      enabled,
      blockchainAvailable,
      hotWallet: {
        address: status?.hotWalletAddress ?? null,
        balance: balance ?? null,
      },
      stats: {
        totalBotOrders: stats.totalOrders,
        totalBotAmount: stats.totalAmount,
      },
    };
  }

  @Post('enable')
  @Public()
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '开启 C2C Bot' })
  async enable() {
    await this.redis.set(C2cBotScheduler.ENABLED_KEY, 'true');
    return {
      success: true,
      enabled: true,
      message: 'C2C Bot 已开启',
    };
  }

  @Post('disable')
  @Public()
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '关闭 C2C Bot' })
  async disable() {
    await this.redis.set(C2cBotScheduler.ENABLED_KEY, 'false');
    return {
      success: true,
      enabled: false,
      message: 'C2C Bot 已关闭',
    };
  }

  @Get('orders')
  @Public()
  @ApiOperation({ summary: '获取 Bot 购买的订单历史' })
  @ApiQuery({ name: 'page', required: false, type: Number })
  @ApiQuery({ name: 'pageSize', required: false, type: Number })
  async getOrders(
    @Query('page') page?: number,
    @Query('pageSize') pageSize?: number,
  ) {
    const result = await this.c2cOrderRepository.findBotPurchasedOrders({
      page: page ?? 1,
      pageSize: pageSize ?? 20,
    });

    return {
      success: true,
      data: result.data.map((order) => ({
        orderNo: order.orderNo,
        makerAccountSequence: order.makerAccountSequence,
        makerPhone: order.makerPhone,
        makerNickname: order.makerNickname,
        totalAmount: order.totalAmount,
        price: order.price,
        quantity: order.quantity,
        sellerKavaAddress: order.sellerKavaAddress,
        paymentTxHash: order.paymentTxHash,
        status: order.status,
        completedAt: order.completedAt,
        createdAt: order.createdAt,
      })),
      total: result.total,
      page: page ?? 1,
      pageSize: pageSize ?? 20,
    };
  }
}
