import { Controller, Get, Param, Query } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { ZodResponse } from 'nestjs-zod';
import { Permission } from '@pac/types';
import { RequirePermission } from '../../common/decorators/permissions.decorator';
import {
  TenantScope,
  TenantScopeContext,
} from '../../common/decorators/tenant-scope.decorator';
import { PatientTimelineResponseDto } from './dto/patient.dto';
import { PatientService } from './patient.service';

@ApiTags('patient')
@ApiBearerAuth('accessToken')
@Controller('patients')
export class PatientController {
  constructor(private readonly patient: PatientService) {}

  @Get(':id/timeline')
  @ZodResponse({ status: 200, type: PatientTimelineResponseDto })
  @RequirePermission(Permission.PATIENT_VIEW)
  @ApiOperation({ summary: 'Patient fact timeline (most recent first)' })
  getTimeline(
    @TenantScope() scope: TenantScopeContext,
    @Param('id') id: string,
    @Query('limit') limitRaw?: string,
  ) {
    const limit = Math.min(Math.max(Number(limitRaw ?? 50), 1), 500);
    return this.patient.getTimeline(scope, id, limit);
  }

  @Get(':id/phone-reveal')
  @RequirePermission(Permission.PATIENT_VIEW)
  @ApiOperation({ summary: 'Reveal masked phone — 拉患者明文手机号(需 PATIENT_VIEW 权限)' })
  revealPhone(
    @TenantScope() scope: TenantScopeContext,
    @Param('id') id: string,
  ) {
    return this.patient.revealPhone(scope, id);
  }
}
