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


/// <summary>
/// Clinical order management: create, list, status transitions, and result recording.
/// </summary>
[ApiController]
[Produces("application/json")]
[Authorize]
public class OrdersController : ControllerBase
{
    private readonly IOrderService _orders;

    public OrdersController(IOrderService orders) => _orders = orders;

    /// <summary>
    /// Creates a new clinical order for an encounter.
    /// </summary>
    [HttpPost("api/v1/encounters/{encounterId:guid}/orders")]
    [AuthorizePermission(ClinicalPermissions.OrdersWrite)]
    [ProducesResponseType(typeof(ApiResponse<Order>), StatusCodes.Status201Created)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status409Conflict)]
    public async Task<IActionResult> Create(Guid encounterId, [FromBody] CreateOrderRequest req)
    {
        var order = await _orders.CreateAsync(encounterId, req);
        return StatusCode(201, ApiResponse<Order>.Created(order));
    }

    /// <summary>
    /// Lists orders for an encounter with optional status filter.
    /// </summary>
    [HttpGet("api/v1/encounters/{encounterId:guid}/orders")]
    [AuthorizePermission(ClinicalPermissions.EncountersRead)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status400BadRequest)]
    public async Task<IActionResult> ListByEncounter(
        Guid encounterId,
        [FromQuery] string? status,
        [FromQuery] int page = 1,
        [FromQuery] int pageSize = 20)
    {
        OrderStatus? parsedStatus = null;
        if (!string.IsNullOrEmpty(status))
        {
            try
            {
                parsedStatus = OrderStatusExtensions.FromDbString(status);
            }
            catch (ArgumentOutOfRangeException)
            {
                return BadRequest(ApiResponse<object>.Fail(400, "Invalid status filter.", "INVALID_STATUS"));
            }
        }

        var result = await _orders.ListByEncounterAsync(encounterId, parsedStatus, 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 single order by id with its encounter.
    /// </summary>
    [HttpGet("api/v1/orders/{id:guid}")]
    [AuthorizePermission(ClinicalPermissions.EncountersRead)]
    [ProducesResponseType(typeof(ApiResponse<Order>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    public async Task<IActionResult> Get(Guid id)
    {
        var order = await _orders.GetByIdAsync(id);
        return Ok(ApiResponse<Order>.Ok(order));
    }

    /// <summary>
    /// Transitions an order to a new status.
    /// </summary>
    [HttpPatch("api/v1/orders/{id:guid}/status")]
    [AuthorizePermission(ClinicalPermissions.OrdersWrite)]
    [ProducesResponseType(typeof(ApiResponse<Order>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status409Conflict)]
    public async Task<IActionResult> TransitionStatus(Guid id, [FromBody] TransitionOrderStatusRequest req)
    {
        var order = await _orders.TransitionStatusAsync(id, req.Status);
        return Ok(ApiResponse<Order>.Ok(order));
    }

    /// <summary>
    /// Records a result for an order, transitioning it to Resulted status.
    /// </summary>
    [HttpPatch("api/v1/orders/{id:guid}/result")]
    [AuthorizePermission(ClinicalPermissions.OrdersWrite)]
    [ProducesResponseType(typeof(ApiResponse<Order>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status409Conflict)]
    public async Task<IActionResult> RecordResult(Guid id, [FromBody] RecordOrderResultRequest req)
    {
        var order = await _orders.RecordResultAsync(id, req);
        return Ok(ApiResponse<Order>.Ok(order));
    }
}
