import {
  Body,
  Controller,
  Get,
  Param,
  Patch,
  Post,
  Query,
  Req,
  UseGuards,
} from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { ClinicOrgGuard } from '../../common/guards/clinic-org.guard';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { CreatePatientDto } from './dto/create-patient.dto';
import { ListPatientsDto } from './dto/list-patients.dto';
import { UpdatePatientDto } from './dto/update-patient.dto';
import { PatientsService } from './patients.service';

@ApiTags('patients')
@ApiBearerAuth('JWT-auth')
@UseGuards(JwtAuthGuard, ClinicOrgGuard)
@Controller('patients')
export class PatientsController {
  constructor(private readonly patientsService: PatientsService) {}

  @Post()
  @ApiOperation({ summary: 'Create or return existing global patient by mobile' })
  create(@Body() createPatientDto: CreatePatientDto, @Req() req) {
    const organizationId = this.patientsService.getOrganizationIdFromUser(req.user);
    return this.patientsService.create(createPatientDto, organizationId);
  }

  @Get()
  @ApiOperation({ summary: 'Search all patients globally' })
  findAll(@Query() query: ListPatientsDto) {
    return this.patientsService.findAll(query);
  }

  @Get(':id/appointments')
  @ApiOperation({
    summary:
      'List this patient\'s appointments for the current clinic (requires TAB_PATIENTS_READ; not gated by appointments permission)',
  })
  listAppointments(@Param('id') id: string, @Req() req: { user: { id: string; organizationId?: string } }) {
    const organizationId = this.patientsService.getOrganizationIdFromUser(req.user);
    return this.patientsService.listAppointments(id, organizationId, req.user.id);
  }

  @Get(':id')
  @ApiOperation({ summary: 'Get one patient by id' })
  findOne(@Param('id') id: string) {
    return this.patientsService.findOne(id);
  }

  @Patch(':id')
  @ApiOperation({ summary: 'Update global patient record' })
  update(@Param('id') id: string, @Body() updatePatientDto: UpdatePatientDto) {
    return this.patientsService.update(id, updatePatientDto);
  }
}
