import {
  Controller,
  Get,
  Post,
  Body,
  Query,
  Param,
  HttpException,
  HttpStatus,
  Req,
} from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiBearerAuth,
  ApiBody,
  ApiQuery,
  ApiParam,
} from '@nestjs/swagger';
import { ManualMiningService } from '../../application/services/manual-mining.service';
import { getClientIp } from '../../shared/utils/get-client-ip';

@ApiTags('Manual Mining')
@ApiBearerAuth()
@Controller('manual-mining')
export class ManualMiningController {
  constructor(private readonly manualMiningService: ManualMiningService) {}

  @Post('calculate')
  @ApiOperation({ summary: '计算手工补发挖矿预估金额' })
  @ApiBody({
    schema: {
      type: 'object',
      required: ['accountSequence', 'adoptionDate'],
      properties: {
        accountSequence: { type: 'string', description: '用户账户序列号' },
        adoptionDate: {
          type: 'string',
          format: 'date',
          description: '认种日期 (YYYY-MM-DD)',
        },
      },
    },
  })
  async calculate(
    @Body() body: { accountSequence: string; adoptionDate: string },
  ) {
    if (!body.accountSequence || !body.adoptionDate) {
      throw new HttpException('账户序列号和认种日期不能为空', HttpStatus.BAD_REQUEST);
    }
    return this.manualMiningService.calculate(body);
  }

  @Post('execute')
  @ApiOperation({ summary: '执行手工补发挖矿（仅超级管理员）' })
  @ApiBody({
    schema: {
      type: 'object',
      required: ['accountSequence', 'adoptionDate', 'reason'],
      properties: {
        accountSequence: { type: 'string', description: '用户账户序列号' },
        adoptionDate: {
          type: 'string',
          format: 'date',
          description: '认种日期 (YYYY-MM-DD)',
        },
        reason: { type: 'string', description: '补发原因（必填）' },
      },
    },
  })
  async execute(
    @Body() body: { accountSequence: string; adoptionDate: string; reason: string },
    @Req() req: any,
  ) {
    if (!body.accountSequence || !body.adoptionDate) {
      throw new HttpException('账户序列号和认种日期不能为空', HttpStatus.BAD_REQUEST);
    }
    if (!body.reason || body.reason.trim().length === 0) {
      throw new HttpException('补发原因不能为空', HttpStatus.BAD_REQUEST);
    }

    const admin = req.admin;
    return this.manualMiningService.execute(
      {
        accountSequence: body.accountSequence,
        adoptionDate: body.adoptionDate,
        operatorId: admin.id,
        operatorName: admin.username,
        reason: body.reason,
      },
      admin.id,
      getClientIp(req),
      req.headers['user-agent'],
    );
  }

  @Get('records')
  @ApiOperation({ summary: '获取手工补发记录列表' })
  @ApiQuery({ name: 'page', required: false, type: Number })
  @ApiQuery({ name: 'pageSize', required: false, type: Number })
  async getRecords(
    @Query('page') page?: number,
    @Query('pageSize') pageSize?: number,
  ) {
    return this.manualMiningService.getRecords(Number(page) || 1, Number(pageSize) || 20);
  }

  @Get('records/:accountSequence')
  @ApiOperation({ summary: '查询指定用户的手工补发记录' })
  @ApiParam({ name: 'accountSequence', type: String })
  async getRecordByAccount(@Param('accountSequence') accountSequence: string) {
    const record =
      await this.manualMiningService.getRecordByAccountSequence(accountSequence);
    if (!record) {
      throw new HttpException('该用户没有手工补发记录', HttpStatus.NOT_FOUND);
    }
    return record;
  }
}
