import { Controller, Get, Post, Param, Logger } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { DepositRepairService } from '@/application/services/deposit-repair.service';

/**
 * 充值修复控制器
 *
 * 内部 API，用于诊断和修复历史遗留充值问题
 */
@ApiTags('Deposit Repair')
@Controller('internal/deposit-repair')
export class DepositRepairController {
  private readonly logger = new Logger(DepositRepairController.name);

  constructor(private readonly repairService: DepositRepairService) {}

  @Get('diagnose')
  @ApiOperation({ summary: '诊断充值状态' })
  @ApiResponse({
    status: 200,
    description: '返回需要修复的充值统计',
  })
  async diagnose() {
    this.logger.log('Running deposit diagnosis...');
    const result = await this.repairService.diagnose();
    this.logger.log(
      `Diagnosis complete: ${result.confirmedNotNotified.length} deposits need repair`,
    );
    return result;
  }

  @Post('repair/:depositId')
  @ApiOperation({ summary: '修复单个充值' })
  @ApiResponse({
    status: 200,
    description: '修复结果',
  })
  async repairDeposit(@Param('depositId') depositId: string) {
    this.logger.log(`Repairing deposit ${depositId}...`);
    const result = await this.repairService.repairDeposit(BigInt(depositId));
    this.logger.log(`Repair result: ${result.message}`);
    return result;
  }

  @Post('repair-all')
  @ApiOperation({ summary: '批量修复所有未通知的充值' })
  @ApiResponse({
    status: 200,
    description: '批量修复结果',
  })
  async repairAll() {
    this.logger.log('Starting batch repair...');
    const result = await this.repairService.repairAll();
    this.logger.log(
      `Batch repair complete: ${result.success}/${result.total} success`,
    );
    return result;
  }

  @Post('reset-failed-outbox')
  @ApiOperation({ summary: '重置失败的 Outbox 事件' })
  @ApiResponse({
    status: 200,
    description: '重置结果',
  })
  async resetFailedOutbox() {
    this.logger.log('Resetting failed outbox events...');
    const result = await this.repairService.resetFailedOutboxEvents();
    this.logger.log(`Reset ${result.reset} failed events`);
    return result;
  }
}
