import { Controller, Get, Post, Param, Body, Req } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth, ApiParam, ApiBody } from '@nestjs/swagger';
import { IsString, IsOptional } from 'class-validator';
import { PrePlantingRestrictionService } from '../../application/services/pre-planting-restriction.service';
import { getClientIp } from '../../shared/utils/get-client-ip';

class UnlockRestrictionDto {
  @IsString()
  @IsOptional()
  reason?: string;
}

/**
 * 预种卖出限制管理接口（管理员端）
 *
 * [2026-03-04] 新增：管理员查询/解除用户的预种卖出限制。
 *
 * GET  /pre-planting-restriction/:accountSequence → 查询限制状态
 * POST /pre-planting-restriction/:accountSequence/unlock → 解除限制（严格审计）
 */
@ApiTags('Pre-planting Restriction')
@ApiBearerAuth()
@Controller('pre-planting-restriction')
export class PrePlantingRestrictionController {
  constructor(private readonly restrictionService: PrePlantingRestrictionService) {}

  @Get(':accountSequence')
  @ApiOperation({ summary: '查询用户预种卖出限制状态' })
  @ApiParam({ name: 'accountSequence', type: String, description: '账户序列' })
  async getRestrictionStatus(@Param('accountSequence') accountSequence: string) {
    return this.restrictionService.getRestrictionStatus(accountSequence);
  }

  @Post(':accountSequence/unlock')
  @ApiOperation({ summary: '管理员手动解除预种卖出限制（操作记录审计日志）' })
  @ApiParam({ name: 'accountSequence', type: String, description: '账户序列' })
  @ApiBody({ type: UnlockRestrictionDto, required: false })
  async unlockRestriction(
    @Param('accountSequence') accountSequence: string,
    @Body() body: UnlockRestrictionDto,
    @Req() req: any,
  ) {
    const adminId = req.admin?.id || req.admin?.username || 'ADMIN_MANUAL';
    await this.restrictionService.unlockRestriction(adminId, accountSequence, body?.reason, getClientIp(req), req.headers['user-agent']);
    return { success: true };
  }
}
