import {
  UseGuards,
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
} from '@nestjs/common';
import {
  ApiBearerAuth,
  ApiOperation,
  ApiParam,
  ApiTags,
} from '@nestjs/swagger';
import { AccessTokenGuard } from '../auth/access-token.guard.js';
import { RolesGuard } from '../auth/roles.guard.js';
import { Roles } from '../auth/roles.decorator.js';
import { Role } from '../generated/prisma/enums.js';
import { UsersService } from './users.service.js';
import { CreateUserDto } from './dto/create-user.dto.js';
import { UpdateUserDto } from './dto/update-user.dto.js';
import { CurrentActor } from '../auth/current-actor.decorator.js';
import type { ActorContext } from '../common/actor-context.js';

/**
 * 用户管理控制器：面向 B 端后台的用户 CRUD。
 */
@ApiTags('用户管理(B端)')
@ApiBearerAuth('bearer')
@Controller('users')
@UseGuards(AccessTokenGuard, RolesGuard)
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  /**
   * 创建用户。
   */
  @Post()
  @Roles(Role.SYSTEM_ADMIN, Role.HOSPITAL_ADMIN)
  @ApiOperation({ summary: '创建用户' })
  create(
    @CurrentActor() actor: ActorContext,
    @Body() createUserDto: CreateUserDto,
  ) {
    return this.usersService.create(actor, createUserDto);
  }

  /**
   * 查询用户列表。
   */
  @Get()
  @Roles(Role.SYSTEM_ADMIN, Role.HOSPITAL_ADMIN, Role.DIRECTOR, Role.LEADER)
  @ApiOperation({ summary: '查询用户列表' })
  findAll(@CurrentActor() actor: ActorContext) {
    return this.usersService.findAll(actor);
  }

  /**
   * 查询用户详情。
   */
  @Get(':id')
  @Roles(Role.SYSTEM_ADMIN, Role.HOSPITAL_ADMIN, Role.DIRECTOR, Role.LEADER)
  @ApiOperation({ summary: '查询用户详情' })
  @ApiParam({ name: 'id', description: '用户 ID' })
  findOne(@CurrentActor() actor: ActorContext, @Param('id') id: string) {
    return this.usersService.findOne(actor, +id);
  }

  /**
   * 更新用户。
   */
  @Patch(':id')
  @Roles(Role.SYSTEM_ADMIN, Role.HOSPITAL_ADMIN)
  @ApiOperation({ summary: '更新用户' })
  @ApiParam({ name: 'id', description: '用户 ID' })
  update(
    @CurrentActor() actor: ActorContext,
    @Param('id') id: string,
    @Body() updateUserDto: UpdateUserDto,
  ) {
    return this.usersService.update(actor, +id, updateUserDto);
  }

  /**
   * 删除用户。
   */
  @Delete(':id')
  @Roles(Role.SYSTEM_ADMIN, Role.HOSPITAL_ADMIN)
  @ApiOperation({ summary: '删除用户' })
  @ApiParam({ name: 'id', description: '用户 ID' })
  remove(@CurrentActor() actor: ActorContext, @Param('id') id: string) {
    return this.usersService.remove(actor, +id);
  }
}
