import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Body,
  Param,
  Query,
  UseGuards,
  Req,
  HttpCode,
  HttpStatus,
} from '@nestjs/common';
import { AdminUsersService } from './admin-users.service';
import { CreateAdminUserDto } from './dto/create-admin-user.dto';
import { UpdateAdminUserDto } from './dto/update-admin-user.dto';
import { QueryAdminUsersDto } from './dto/query-admin-users.dto';
import { AdminAuthGuard } from '../../common/guards/admin-auth.guard';
import { AdminRolesGuard } from '../../common/guards/admin-roles.guard';
import { AdminRoles } from '../../common/decorators/admin-roles.decorator';
import { AdminRole } from '../../common/types/admin-role.enum';
import type { Request } from 'express';

@ApiTags('admin-users')
@Controller('admin-api/admin-users')
@UseGuards(AdminAuthGuard, AdminRolesGuard)
export class AdminUsersController {
  constructor(private readonly adminUsersService: AdminUsersService) {}

  @Get()
  @AdminRoles(AdminRole.ADMIN)
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取管理员列表' })
  async list(@Query() query: QueryAdminUsersDto) {
    return this.adminUsersService.list(query);
  }

  @Get(':id')
  @AdminRoles(AdminRole.ADMIN)
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取管理员详情' })
  async getById(@Param('id') id: string) {
    return this.adminUsersService.getById(id);
  }

  @Post()
  @AdminRoles(AdminRole.SUPER_ADMIN)
  @ApiBearerAuth()
  @ApiOperation({ summary: '创建管理员' })
  async create(@Body() dto: CreateAdminUserDto, @Req() req: Request) {
    const adminUser = (req as any).adminUser;
    return this.adminUsersService.create(dto, adminUser.id, req.ip, req.headers['user-agent']);
  }

  @Put(':id')
  @AdminRoles(AdminRole.SUPER_ADMIN)
  @HttpCode(HttpStatus.OK)
  @ApiBearerAuth()
  @ApiOperation({ summary: '更新管理员' })
  async update(
    @Param('id') id: string,
    @Body() dto: UpdateAdminUserDto,
    @Req() req: Request,
  ) {
    const adminUser = (req as any).adminUser;
    return this.adminUsersService.update(id, dto, adminUser.id, req.ip, req.headers['user-agent']);
  }

  @Delete(':id')
  @AdminRoles(AdminRole.SUPER_ADMIN)
  @HttpCode(HttpStatus.OK)
  @ApiBearerAuth()
  @ApiOperation({ summary: '删除管理员' })
  async delete(@Param('id') id: string, @Req() req: Request) {
    const adminUser = (req as any).adminUser;
    await this.adminUsersService.delete(id, adminUser.id, req.ip, req.headers['user-agent']);
    return { success: true, message: '已删除管理员' };
  }
}
