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 this clinic’s 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 patients created by the current clinic' })
  findAll(@Query() query: ListPatientsDto, @Req() req) {
    const organizationId = this.patientsService.getOrganizationIdFromUser(req.user);
    return this.patientsService.findAll(query, organizationId);
  }

  @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 created by the current clinic' })
  findOne(@Param('id') id: string, @Req() req) {
    const organizationId = this.patientsService.getOrganizationIdFromUser(req.user);
    return this.patientsService.findOne(id, organizationId);
  }

  @Patch(':id')
  @ApiOperation({ summary: 'Update a patient created by the current clinic' })
  update(
    @Param('id') id: string,
    @Body() updatePatientDto: UpdatePatientDto,
    @Req() req,
  ) {
    const organizationId = this.patientsService.getOrganizationIdFromUser(req.user);
    return this.patientsService.update(id, updatePatientDto, organizationId);
  }
}
