import { Controller, Get, Put, Param, Query, Body, Req } from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiBearerAuth,
  ApiParam,
  ApiQuery,
} from '@nestjs/swagger';
import { CapabilityAdminService, SetCapabilityDto } from '../../application/services/capability-admin.service';
import { getClientIp } from '../../shared/utils/get-client-ip';

@ApiTags('Capabilities')
@ApiBearerAuth()
@Controller('capabilities')
export class CapabilityController {
  constructor(private readonly capabilityAdminService: CapabilityAdminService) {}

  @Get('users/:accountSequence')
  @ApiOperation({ summary: '查询用户能力列表' })
  @ApiParam({ name: 'accountSequence', type: String })
  async getCapabilities(@Param('accountSequence') accountSequence: string) {
    return this.capabilityAdminService.getCapabilities(accountSequence);
  }

  @Put('users/:accountSequence')
  @ApiOperation({ summary: '设置用户单个能力' })
  @ApiParam({ name: 'accountSequence', type: String })
  async setCapability(
    @Param('accountSequence') accountSequence: string,
    @Body() dto: SetCapabilityDto,
    @Req() req: any,
  ) {
    const adminId = req.admin?.id || req.admin?.username || 'unknown';
    return this.capabilityAdminService.setCapability(accountSequence, dto, adminId, getClientIp(req), req.headers['user-agent']);
  }

  @Put('users/:accountSequence/bulk')
  @ApiOperation({ summary: '批量设置用户能力' })
  @ApiParam({ name: 'accountSequence', type: String })
  async setCapabilities(
    @Param('accountSequence') accountSequence: string,
    @Body() body: { capabilities: SetCapabilityDto[] },
    @Req() req: any,
  ) {
    const adminId = req.admin?.id || req.admin?.username || 'unknown';
    return this.capabilityAdminService.setCapabilities(
      accountSequence,
      body.capabilities,
      adminId,
      getClientIp(req),
      req.headers['user-agent'],
    );
  }

  @Get('users/:accountSequence/logs')
  @ApiOperation({ summary: '查询能力变更日志' })
  @ApiParam({ name: 'accountSequence', type: String })
  @ApiQuery({ name: 'page', required: false, type: Number })
  @ApiQuery({ name: 'pageSize', required: false, type: Number })
  async getCapabilityLogs(
    @Param('accountSequence') accountSequence: string,
    @Query('page') page?: string,
    @Query('pageSize') pageSize?: string,
  ) {
    return this.capabilityAdminService.getCapabilityLogs(
      accountSequence,
      parseInt(page || '1', 10),
      parseInt(pageSize || '20', 10),
    );
  }
}
