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 { HospitalsService } from './hospitals.service.js';
import { CreateHospitalDto } from './dto/create-hospital.dto.js';
import { UpdateHospitalDto } from './dto/update-hospital.dto.js';
import { OrganizationQueryDto } from '../organization-common/dto/organization-query.dto.js';

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

  /**
   * 创建医院（仅系统管理员）。
   */
  @Post()
  @Roles(Role.SYSTEM_ADMIN)
  @ApiOperation({ summary: '创建医院（SYSTEM_ADMIN）' })
  create(@CurrentActor() actor: ActorContext, @Body() dto: CreateHospitalDto) {
    return this.hospitalsService.create(actor, dto);
  }

  /**
   * 查询医院列表（系统管理员全量，院管仅本院）。
   */
  @Get()
  @Roles(Role.SYSTEM_ADMIN, Role.HOSPITAL_ADMIN, Role.DIRECTOR, Role.LEADER)
  @ApiOperation({ summary: '查询医院列表' })
  findAll(
    @CurrentActor() actor: ActorContext,
    @Query() query: OrganizationQueryDto,
  ) {
    return this.hospitalsService.findAll(actor, query);
  }

  /**
   * 查询医院详情。
   */
  @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', ParseIntPipe) id: number,
  ) {
    return this.hospitalsService.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: UpdateHospitalDto,
  ) {
    return this.hospitalsService.update(actor, id, dto);
  }

  /**
   * 删除医院（仅系统管理员）。
   */
  @Delete(':id')
  @Roles(Role.SYSTEM_ADMIN)
  @ApiOperation({ summary: '删除医院（SYSTEM_ADMIN）' })
  remove(
    @CurrentActor() actor: ActorContext,
    @Param('id', ParseIntPipe) id: number,
  ) {
    return this.hospitalsService.remove(actor, id);
  }
}
