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


/// <summary>
/// Patient registration, search, and encounter opening.
/// </summary>
[ApiController]
[Route("api/v1/patients")]
[Produces("application/json")]
[Authorize]
public class PatientsController : ControllerBase
{
    private readonly IPatientService _patients;

    public PatientsController(IPatientService patients) => _patients = patients;

    /// <summary>
    /// Registers a new patient and assigns a system-generated MRN.
    /// </summary>
    /// <param name="req">Patient demographics.</param>
    /// <returns>The created patient record.</returns>
    [HttpPost]
    [AuthorizePermission(ClinicalPermissions.PatientsWrite)]
    [ProducesResponseType(typeof(ApiResponse<Patient>), StatusCodes.Status201Created)]
    public async Task<IActionResult> Register([FromBody] RegisterPatientRequest req)
    {
        var patient = await _patients.RegisterAsync(req);
        return StatusCode(201, ApiResponse<Patient>.Created(patient));
    }

    /// <summary>
    /// Lists patients with optional MRN or name search and pagination.
    /// </summary>
    /// <param name="q">MRN (exact) or name substring (ILIKE).</param>
    /// <param name="page">Page number (1-based).</param>
    /// <param name="pageSize">Results per page.</param>
    /// <returns>A paginated list of patients.</returns>
    [HttpGet]
    [AuthorizePermission(ClinicalPermissions.PatientsRead)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
    public async Task<IActionResult> List([FromQuery] string? q, [FromQuery] int page = 1, [FromQuery] int pageSize = 20)
    {
        var result = await _patients.ListAsync(q, page, pageSize);
        return Ok(ApiResponse<object>.Ok(new
        {
            items = result.Items,
            page = result.Page,
            pageSize = result.PageSize,
            totalCount = result.TotalCount,
            totalPages = result.TotalPages
        }));
    }

    /// <summary>
    /// Gets a patient by id, including active encounters.
    /// </summary>
    /// <param name="id">Patient id.</param>
    /// <returns>The patient record.</returns>
    [HttpGet("{id:guid}")]
    [AuthorizePermission(ClinicalPermissions.PatientsRead)]
    [ProducesResponseType(typeof(ApiResponse<Patient>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    public async Task<IActionResult> Get(Guid id)
    {
        var patient = await _patients.GetByIdAsync(id);
        return Ok(ApiResponse<Patient>.Ok(patient));
    }

    /// <summary>
    /// Updates patient demographics. Only non-null fields are applied.
    /// </summary>
    /// <param name="id">Patient id.</param>
    /// <param name="req">Fields to update.</param>
    /// <returns>The updated patient record.</returns>
    [HttpPatch("{id:guid}")]
    [AuthorizePermission(ClinicalPermissions.PatientsWrite)]
    [ProducesResponseType(typeof(ApiResponse<Patient>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    public async Task<IActionResult> Update(Guid id, [FromBody] UpdatePatientRequest req)
    {
        var patient = await _patients.UpdateAsync(id, req);
        return Ok(ApiResponse<Patient>.Ok(patient));
    }

    /// <summary>
    /// Opens a new active encounter for the patient.
    /// </summary>
    /// <param name="id">Patient id.</param>
    /// <param name="req">Encounter type, department, and attending physician.</param>
    /// <returns>The created encounter.</returns>
    [HttpPost("{id:guid}/encounters")]
    [AuthorizePermission(ClinicalPermissions.EncountersWrite)]
    [ProducesResponseType(typeof(ApiResponse<Encounter>), StatusCodes.Status201Created)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status409Conflict)]
    public async Task<IActionResult> OpenEncounter(Guid id, [FromBody] OpenEncounterRequest req)
    {
        var encounter = await _patients.OpenEncounterAsync(id, req);
        return StatusCode(201, ApiResponse<Encounter>.Created(encounter));
    }
}
