import { Controller, Get, Post, Param, Body } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiParam, ApiResponse, ApiBody } from '@nestjs/swagger';
import { IsString, IsOptional } from 'class-validator';
import { SellRestrictionService } from '../../pre-planting/application/services/sell-restriction.service';
import { Public } from '../../shared/guards/jwt-auth.guard';

class UnlockRestrictionDto {
  @IsString()
  unlockedBy: string;

  @IsString()
  @IsOptional()
  reason?: string;
}

/**
 * 预种卖出限制接口
 *
 * [2026-03-04] 新增：内部接口，供 trading-service 和 mining-admin-service 调用。
 *
 * GET  /api/v2/pre-planting/sell-restriction/:accountSequence
 *   → { isRestricted: boolean }（Public，供 trading-service 调用）
 *
 * POST /api/v2/pre-planting/sell-restriction/:accountSequence/unlock
 *   → { success: true }（Public，内部服务间调用，依赖网络隔离保护）
 */
@ApiTags('Pre-planting Sell Restriction')
@Controller('pre-planting/sell-restriction')
export class PrePlantingRestrictionController {
  constructor(private readonly sellRestrictionService: SellRestrictionService) {}

  /**
   * 查询预种卖出限制状态
   * 标记为 @Public 以便 trading-service 无需 JWT 即可调用
   */
  @Get(':accountSequence')
  @Public()
  @ApiOperation({ summary: '查询账户预种卖出限制状态' })
  @ApiParam({ name: 'accountSequence', description: '账户序列' })
  @ApiResponse({ status: 200, description: '{ isRestricted: boolean }' })
  async getRestriction(
    @Param('accountSequence') accountSequence: string,
  ): Promise<{ isRestricted: boolean }> {
    const isRestricted = await this.sellRestrictionService.isRestricted(accountSequence);
    return { isRestricted };
  }

  /**
   * 管理员手动解除卖出限制
   * 标记为 @Public，依赖 Docker 内网隔离（仅 mining-admin-service 可达）
   */
  @Post(':accountSequence/unlock')
  @Public()
  @ApiOperation({ summary: '管理员手动解除预种卖出限制' })
  @ApiParam({ name: 'accountSequence', description: '账户序列' })
  @ApiBody({ type: UnlockRestrictionDto })
  @ApiResponse({ status: 201, description: '{ success: true }' })
  async unlock(
    @Param('accountSequence') accountSequence: string,
    @Body() body: UnlockRestrictionDto,
  ): Promise<{ success: boolean }> {
    await this.sellRestrictionService.createOverride(accountSequence, body.unlockedBy, body.reason);
    return { success: true };
  }
}
