using ERPCore.Domain.Enums;
using ERPCore.Dtos.Common;
using ERPCore.Dtos.Procurement;
using ERPCore.Services.Interfaces;
using Microsoft.AspNetCore.Mvc;

namespace ERPCore.Controllers;

/// <summary>Purchase-requisition endpoints (docs/11 §3.1).</summary>
[Route("api/v1/requisitions")]
public sealed class RequisitionsController : ApiControllerBase
{
    private readonly IRequisitionService _requisitions;

    public RequisitionsController(IRequisitionService requisitions) => _requisitions = requisitions;

    [HttpGet]
    [ProducesResponseType(typeof(PagedResponse<RequisitionSummaryDto>), StatusCodes.Status200OK)]
    public async Task<ActionResult<PagedResponse<RequisitionSummaryDto>>> List(
        [FromQuery] PageQuery query, [FromQuery] RequisitionStatus? status, CancellationToken ct)
        => Ok(await _requisitions.ListAsync(query, status, ct));

    [HttpGet("{requisitionId:int}")]
    [ProducesResponseType(typeof(RequisitionDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<ActionResult<RequisitionDto>> GetById(int requisitionId, CancellationToken ct)
    {
        var dto = await _requisitions.GetAsync(requisitionId, ct);
        return dto is null ? NotFound() : Ok(dto);
    }

    [HttpPost]
    [ProducesResponseType(typeof(RequisitionDto), StatusCodes.Status201Created)]
    [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)]
    public async Task<ActionResult<RequisitionDto>> Create([FromBody] CreateRequisitionRequest request, CancellationToken ct)
    {
        var dto = await _requisitions.CreateAsync(request, ct);
        return Created($"/api/v1/requisitions/{dto.RequisitionId}", dto);
    }

    [HttpPost("{requisitionId:int}/submit")]
    [ProducesResponseType(typeof(RequisitionDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<ActionResult<RequisitionDto>> Submit(int requisitionId, CancellationToken ct)
        => Ok(await _requisitions.SubmitAsync(requisitionId, ct));
}
