using ERPCore.Dtos.Common;
using ERPCore.Dtos.Stock;
using ERPCore.Services.Interfaces;
using Microsoft.AspNetCore.Mvc;

namespace ERPCore.Controllers;

/// <summary>Stock-adjustment endpoints (docs/11 §5.5).</summary>
[Route("api/v1/stock-adjustments")]
public sealed class StockAdjustmentsController : ApiControllerBase
{
    private readonly IAdjustmentService _adjustments;

    public StockAdjustmentsController(IAdjustmentService adjustments) => _adjustments = adjustments;

    /// <summary>List posted adjustments, newest first.</summary>
    [HttpGet]
    [ProducesResponseType(typeof(PagedResponse<AdjustmentSummaryDto>), StatusCodes.Status200OK)]
    public async Task<ActionResult<PagedResponse<AdjustmentSummaryDto>>> List(
        [FromQuery] PageQuery query, [FromQuery] int? warehouseId, [FromQuery] int? reasonCodeId, CancellationToken ct)
        => Ok(await _adjustments.ListAsync(query, warehouseId, reasonCodeId, ct));

    /// <summary>Get one adjustment with its lines and the ledger entries it posted.</summary>
    [HttpGet("{adjustmentId:int}")]
    [ProducesResponseType(typeof(AdjustmentDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<ActionResult<AdjustmentDto>> GetById(int adjustmentId, CancellationToken ct)
    {
        var dto = await _adjustments.GetAsync(adjustmentId, ct);
        return dto is null ? NotFound() : Ok(dto);
    }

    /// <summary>Create + auto-post an adjustment (mandatory reason code; decrease FIFO-consumes).</summary>
    [HttpPost]
    [ProducesResponseType(typeof(AdjustmentDto), StatusCodes.Status201Created)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    [ProducesResponseType(StatusCodes.Status409Conflict)]
    [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)]
    public async Task<ActionResult<AdjustmentDto>> Create([FromBody] CreateAdjustmentRequest request, CancellationToken ct)
    {
        var dto = await _adjustments.CreateAsync(request, ct);
        return Created($"/api/v1/stock-adjustments/{dto.AdjustmentId}", dto);
    }
}
