import {
  Controller,
  Get,
  Post,
  Put,
  Body,
  Query,
  HttpCode,
  HttpStatus,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { IsNumber, IsString, IsBoolean, IsOptional } from 'class-validator';
import { TreePricingService } from './tree-pricing.service';

// ======================== DTO ========================

class UpdateSupplementDto {
  /** 新的加价金额（整数 USDT） */
  @IsNumber()
  newSupplement: number;
  /** 变更原因 */
  @IsString()
  reason: string;
  /** 操作人ID */
  @IsOptional()
  @IsString()
  operatorId?: string;
}

class UpdateAutoIncreaseDto {
  /** 是否启用自动涨价 */
  @IsBoolean()
  enabled: boolean;
  /** 每次自动涨价金额（整数 USDT） */
  @IsOptional()
  @IsNumber()
  amount?: number;
  /** 自动涨价间隔天数 */
  @IsOptional()
  @IsNumber()
  intervalDays?: number;
  /** 操作人ID */
  @IsOptional()
  @IsString()
  operatorId?: string;
}

class ChangeLogQueryDto {
  @IsOptional()
  @IsNumber()
  page?: number;
  @IsOptional()
  @IsNumber()
  pageSize?: number;
}

// ======================== Admin Controller ========================

@ApiTags('认种定价配置')
@Controller('admin/tree-pricing')
export class AdminTreePricingController {
  constructor(
    private readonly pricingService: TreePricingService,
  ) {}

  @Get('config')
  @ApiOperation({ summary: '获取当前定价配置' })
  @ApiResponse({ status: HttpStatus.OK, description: '定价配置信息' })
  async getConfig() {
    return this.pricingService.getConfig();
  }

  @Post('supplement')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '手动修改加价金额（总部运营成本压力涨价）' })
  @ApiResponse({ status: HttpStatus.OK, description: '更新成功，返回最新配置' })
  async updateSupplement(@Body() dto: UpdateSupplementDto) {
    return this.pricingService.updateSupplement(
      dto.newSupplement,
      dto.reason,
      dto.operatorId || 'admin',
    );
  }

  @Put('auto-increase')
  @ApiOperation({ summary: '设置自动涨价（总部运营成本压力自动涨价）' })
  @ApiResponse({ status: HttpStatus.OK, description: '设置成功，返回最新配置' })
  async updateAutoIncrease(@Body() dto: UpdateAutoIncreaseDto) {
    return this.pricingService.updateAutoIncreaseSettings(
      dto.enabled,
      dto.amount,
      dto.intervalDays,
      dto.operatorId || 'admin',
    );
  }

  @Get('change-log')
  @ApiOperation({ summary: '获取价格变更审计日志' })
  @ApiResponse({ status: HttpStatus.OK, description: '分页审计日志' })
  async getChangeLog(@Query() query: ChangeLogQueryDto) {
    return this.pricingService.getChangeLog(
      Number(query.page) || 1,
      Number(query.pageSize) || 20,
    );
  }
}

// ======================== Public Controller ========================

/**
 * 公开 API（供 planting-service 和 mobile-app 调用）
 * 不需要管理员认证
 */
@ApiTags('认种定价配置-公开API')
@Controller('tree-pricing')
export class PublicTreePricingController {
  constructor(
    private readonly pricingService: TreePricingService,
  ) {}

  @Get('config')
  @ApiOperation({ summary: '获取当前定价配置（公开接口）' })
  async getConfig() {
    return this.pricingService.getConfig();
  }
}
