using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

/// <summary>
/// Patient registry search and digitization history.
/// </summary>
[ApiController]
[Route("api/v1/patients")]
[Produces("application/json")]
[Authorize]
public class PatientsController : ControllerBase
{
    private readonly IDigitizationHistoryService _history;
    private readonly IPatientRegistryService _patients;

    public PatientsController(
        IDigitizationHistoryService history,
        IPatientRegistryService patients)
    {
        _history = history;
        _patients = patients;
    }

    /// <summary>
    /// Searches live patients by MRN or full name (minimum 2 characters).
    /// </summary>
    [HttpGet("search")]
    [Authorize(Roles = "INTAKE_CLERK,CLINICIAN,ADMINISTRATOR")]
    [ProducesResponseType(typeof(ApiResponse<IReadOnlyList<PatientSearchResult>>), StatusCodes.Status200OK)]
    public async Task<IActionResult> Search([FromQuery] string q)
    {
        var results = await _patients.SearchAsync(q ?? string.Empty);
        return Ok(ApiResponse<IReadOnlyList<PatientSearchResult>>.Ok(results));
    }

    /// <summary>
    /// Returns the complete digitization history for a patient, including all
    /// batches, their promotion status, correction chains, and per-batch audit trails.
    /// Superseded observations are included with their supersession metadata.
    /// </summary>
    [HttpGet("{patientId:guid}/digitization-history")]
    [ProducesResponseType(typeof(ApiResponse<PatientDigitizationHistoryResponse>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    public async Task<IActionResult> GetDigitizationHistory(Guid patientId)
    {
        var history = await _history.GetPatientHistoryAsync(patientId);
        return Ok(ApiResponse<PatientDigitizationHistoryResponse>.Ok(history));
    }
}
