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

namespace ERPCore.Controllers;

/// <summary>Purchase-return endpoints (docs/11 §3.4).</summary>
[Route("api/v1/purchase-returns")]
public sealed class PurchaseReturnsController : ApiControllerBase
{
    private readonly IPurchaseReturnService _returns;

    public PurchaseReturnsController(IPurchaseReturnService returns) => _returns = returns;

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

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

    /// <summary>Create + auto-post a return (outbound movement). 409 if return exceeds available stock.</summary>
    [HttpPost]
    [ProducesResponseType(typeof(PurchaseReturnDto), StatusCodes.Status201Created)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    [ProducesResponseType(StatusCodes.Status409Conflict)]
    [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)]
    public async Task<ActionResult<PurchaseReturnDto>> Create([FromBody] CreatePurchaseReturnRequest request, CancellationToken ct)
    {
        var dto = await _returns.CreateAsync(request, ct);
        return Created($"/api/v1/purchase-returns/{dto.ReturnId}", dto);
    }
}
