import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  ParseIntPipe,
  Patch,
  Post,
  Query,
  UseGuards,
} from '@nestjs/common';
import {
  ApiBearerAuth,
  ApiOperation,
  ApiParam,
  ApiQuery,
  ApiTags,
} from '@nestjs/swagger';
import type { ActorContext } from '../common/actor-context.js';
import { AccessTokenGuard } from '../auth/access-token.guard.js';
import { CurrentActor } from '../auth/current-actor.decorator.js';
import { Roles } from '../auth/roles.decorator.js';
import { RolesGuard } from '../auth/roles.guard.js';
import { Role } from '../generated/prisma/enums.js';
import { DepartmentsService } from './departments.service.js';
import { CreateDepartmentDto } from './dto/create-department.dto.js';
import { UpdateDepartmentDto } from './dto/update-department.dto.js';
import { OrganizationQueryDto } from '../organization-common/dto/organization-query.dto.js';

/**
 * 科室管理控制器：拆分自组织大控制器，专注科室资源。
 */
@ApiTags('科室管理(B端)')
@ApiBearerAuth('bearer')
@Controller('b/organization/departments')
@UseGuards(AccessTokenGuard, RolesGuard)
export class DepartmentsController {
  constructor(private readonly departmentsService: DepartmentsService) {}

  /**
   * 创建科室。
   */
  @Post()
  @Roles(Role.SYSTEM_ADMIN, Role.HOSPITAL_ADMIN)
  @ApiOperation({ summary: '创建科室' })
  create(
    @CurrentActor() actor: ActorContext,
    @Body() dto: CreateDepartmentDto,
  ) {
    return this.departmentsService.create(actor, dto);
  }

  /**
   * 查询科室列表。
   */
  @Get()
  @Roles(
    Role.SYSTEM_ADMIN,
    Role.HOSPITAL_ADMIN,
    Role.DIRECTOR,
    Role.LEADER,
    Role.DOCTOR,
  )
  @ApiOperation({ summary: '查询科室列表' })
  @ApiQuery({ name: 'hospitalId', required: false, description: '医院 ID' })
  findAll(
    @CurrentActor() actor: ActorContext,
    @Query() query: OrganizationQueryDto,
  ) {
    return this.departmentsService.findAll(actor, query);
  }

  /**
   * 查询科室详情。
   */
  @Get(':id')
  @Roles(
    Role.SYSTEM_ADMIN,
    Role.HOSPITAL_ADMIN,
    Role.DIRECTOR,
    Role.LEADER,
    Role.DOCTOR,
  )
  @ApiOperation({ summary: '查询科室详情' })
  @ApiParam({ name: 'id', description: '科室 ID' })
  findOne(
    @CurrentActor() actor: ActorContext,
    @Param('id', ParseIntPipe) id: number,
  ) {
    return this.departmentsService.findOne(actor, id);
  }

  /**
   * 更新科室。
   */
  @Patch(':id')
  @Roles(Role.SYSTEM_ADMIN, Role.HOSPITAL_ADMIN)
  @ApiOperation({ summary: '更新科室' })
  update(
    @CurrentActor() actor: ActorContext,
    @Param('id', ParseIntPipe) id: number,
    @Body() dto: UpdateDepartmentDto,
  ) {
    return this.departmentsService.update(actor, id, dto);
  }

  /**
   * 删除科室。
   */
  @Delete(':id')
  @Roles(Role.SYSTEM_ADMIN, Role.HOSPITAL_ADMIN)
  @ApiOperation({ summary: '删除科室' })
  remove(
    @CurrentActor() actor: ActorContext,
    @Param('id', ParseIntPipe) id: number,
  ) {
    return this.departmentsService.remove(actor, id);
  }
}
