import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  ParseIntPipe,
  Patch,
  Post,
  Query,
  UseGuards,
} from '@nestjs/common';
import {
  ApiBearerAuth,
  ApiOperation,
  ApiParam,
  ApiQuery,
  ApiTags,
} from '@nestjs/swagger';
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 type { ActorContext } from '../../common/actor-context.js';
import { Role } from '../../generated/prisma/enums.js';
import { CreateDictionaryItemDto } from '../dto/create-dictionary-item.dto.js';
import { DictionaryQueryDto } from '../dto/dictionary-query.dto.js';
import { UpdateDictionaryItemDto } from '../dto/update-dictionary-item.dto.js';
import { DictionariesService } from '../dictionaries.service.js';

/**
 * B 端字典控制器：供患者表单读取和系统管理员维护选项字典。
 */
@ApiTags('字典管理(B端)')
@ApiBearerAuth('bearer')
@Controller('b/dictionaries')
@UseGuards(AccessTokenGuard, RolesGuard)
export class BDictionariesController {
  constructor(private readonly dictionariesService: DictionariesService) {}

  /**
   * 查询字典项列表。
   */
  @Get()
  @Roles(
    Role.SYSTEM_ADMIN,
    Role.HOSPITAL_ADMIN,
    Role.DIRECTOR,
    Role.LEADER,
    Role.DOCTOR,
    Role.ENGINEER,
  )
  @ApiOperation({ summary: '查询系统字典' })
  @ApiQuery({
    name: 'type',
    required: false,
    description: '字典类型，不传返回全部类型',
  })
  @ApiQuery({
    name: 'includeDisabled',
    required: false,
    description: '是否包含停用项，仅系统管理员生效',
  })
  findAll(
    @CurrentActor() actor: ActorContext,
    @Query() query: DictionaryQueryDto,
  ) {
    return this.dictionariesService.findAll(actor, query);
  }

  /**
   * 创建字典项。
   */
  @Post()
  @Roles(Role.SYSTEM_ADMIN)
  @ApiOperation({ summary: '创建系统字典项（SYSTEM_ADMIN）' })
  create(
    @CurrentActor() actor: ActorContext,
    @Body() dto: CreateDictionaryItemDto,
  ) {
    return this.dictionariesService.create(actor, dto);
  }

  /**
   * 更新字典项。
   */
  @Patch(':id')
  @Roles(Role.SYSTEM_ADMIN)
  @ApiOperation({ summary: '更新系统字典项（SYSTEM_ADMIN）' })
  @ApiParam({ name: 'id', description: '字典项 ID' })
  update(
    @CurrentActor() actor: ActorContext,
    @Param('id', ParseIntPipe) id: number,
    @Body() dto: UpdateDictionaryItemDto,
  ) {
    return this.dictionariesService.update(actor, id, dto);
  }

  /**
   * 删除字典项。
   */
  @Delete(':id')
  @Roles(Role.SYSTEM_ADMIN)
  @ApiOperation({ summary: '删除系统字典项（SYSTEM_ADMIN）' })
  @ApiParam({ name: 'id', description: '字典项 ID' })
  remove(
    @CurrentActor() actor: ActorContext,
    @Param('id', ParseIntPipe) id: number,
  ) {
    return this.dictionariesService.remove(actor, id);
  }
}
