package com.gnx.telemedicine.controller;

import com.gnx.telemedicine.annotation.LogPhiAccess;
import com.gnx.telemedicine.dto.medical.VitalSignsRequestDto;
import com.gnx.telemedicine.dto.medical.VitalSignsResponseDto;
import com.gnx.telemedicine.service.VitalSignsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/v3/vital-signs")
@RequiredArgsConstructor
@Tag(name = "Vital Signs", description = "Endpoints for managing patient vital signs")
@SecurityRequirement(name = "bearerAuth")
public class VitalSignsController {
    
    private final VitalSignsService vitalSignsService;

    @Operation(
            summary = "Get vital signs by patient ID",
            description = "Retrieve all vital signs records for a specific patient.",
            parameters = @Parameter(name = "patientId", description = "Patient ID", required = true)
    )
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = "200",
                    description = "List of vital signs retrieved successfully",
                    content = @Content(
                            mediaType = "application/json",
                            array = @ArraySchema(schema = @Schema(implementation = VitalSignsResponseDto.class))
                    )
            )
    })
    @LogPhiAccess(
            resourceType = "VITAL_SIGNS",
            patientIdParam = "patientId",
            accessType = "Treatment",
            accessedFields = {"temperature", "bloodPressureSystolic", "bloodPressureDiastolic", "heartRate", "oxygenSaturation"}
    )
    @GetMapping("/patient/{patientId}")
    public ResponseEntity<List<VitalSignsResponseDto>> getVitalSignsByPatientId(
            @PathVariable UUID patientId) {
        return ResponseEntity.ok(vitalSignsService.getVitalSignsByPatientId(patientId));
    }

    @Operation(
            summary = "Get latest vital signs by patient ID",
            description = "Retrieve the most recent vital signs record for a patient."
    )
    @GetMapping("/patient/{patientId}/latest")
    public ResponseEntity<VitalSignsResponseDto> getLatestVitalSignsByPatientId(
            @PathVariable UUID patientId) {
        VitalSignsResponseDto vitalSigns = vitalSignsService.getLatestVitalSignsByPatientId(patientId);
        if (vitalSigns == null) {
            return ResponseEntity.notFound().build(); // Return 404 when no vital signs found
        }
        return ResponseEntity.ok(vitalSigns);
    }

    @Operation(
            summary = "Get vital signs by appointment ID",
            description = "Retrieve vital signs recorded during a specific appointment."
    )
    @GetMapping("/appointment/{appointmentId}")
    public ResponseEntity<List<VitalSignsResponseDto>> getVitalSignsByAppointmentId(
            @PathVariable UUID appointmentId) {
        return ResponseEntity.ok(vitalSignsService.getVitalSignsByAppointmentId(appointmentId));
    }

    @Operation(
            summary = "Create vital signs record",
            description = "Record new vital signs for a patient. BMI is automatically calculated if weight and height are provided.",
            requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
                    description = "Vital signs data",
                    required = true,
                    content = @Content(schema = @Schema(implementation = VitalSignsRequestDto.class))
            )
    )
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = "200",
                    description = "Vital signs recorded successfully",
                    content = @Content(schema = @Schema(implementation = VitalSignsResponseDto.class))
            ),
            @ApiResponse(responseCode = "400", description = "Validation error")
    })
    @PostMapping
    public ResponseEntity<VitalSignsResponseDto> createVitalSigns(
            Authentication authentication,
            @RequestBody @Valid VitalSignsRequestDto requestDto) {
        String userEmail = authentication.getName();
        VitalSignsResponseDto response = vitalSignsService.createVitalSigns(userEmail, requestDto);
        return ResponseEntity.ok(response);
    }

    @Operation(
            summary = "Get vital signs by ID",
            description = "Retrieve a specific vital signs record by its ID."
    )
    @GetMapping("/{id}")
    public ResponseEntity<VitalSignsResponseDto> getVitalSignsById(@PathVariable UUID id) {
        return ResponseEntity.ok(vitalSignsService.getVitalSignsById(id));
    }

    @Operation(
            summary = "Delete vital signs record",
            description = "Delete a vital signs record by ID."
    )
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteVitalSigns(@PathVariable UUID id) {
        vitalSignsService.deleteVitalSigns(id);
        return ResponseEntity.noContent().build();
    }
}

