import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  ParseIntPipe,
  Patch,
  Post,
  Query,
  UseGuards,
} from '@nestjs/common';
import {
  ApiBearerAuth,
  ApiOperation,
  ApiParam,
  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 { GroupsService } from './groups.service.js';
import { CreateGroupDto } from './dto/create-group.dto.js';
import { UpdateGroupDto } from './dto/update-group.dto.js';
import { OrganizationQueryDto } from '../organization-common/dto/organization-query.dto.js';

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

  /**
   * 创建小组。
   */
  @Post()
  @Roles(Role.SYSTEM_ADMIN, Role.HOSPITAL_ADMIN)
  @ApiOperation({ summary: '创建小组' })
  create(@CurrentActor() actor: ActorContext, @Body() dto: CreateGroupDto) {
    return this.groupsService.create(actor, dto);
  }

  /**
   * 查询小组列表。
   */
  @Get()
  @Roles(
    Role.SYSTEM_ADMIN,
    Role.HOSPITAL_ADMIN,
    Role.DIRECTOR,
    Role.LEADER,
    Role.DOCTOR,
  )
  @ApiOperation({ summary: '查询小组列表' })
  findAll(
    @CurrentActor() actor: ActorContext,
    @Query() query: OrganizationQueryDto,
  ) {
    return this.groupsService.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.groupsService.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: UpdateGroupDto,
  ) {
    return this.groupsService.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.groupsService.remove(actor, id);
  }
}
