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

namespace ERPCore.Controllers;

/// <summary>Sales-return endpoints — customer returns of previously sold goods.</summary>
[Route("api/v1/sales-returns")]
public sealed class SalesReturnsController : ApiControllerBase
{
    private readonly ISalesReturnService _returns;

    public SalesReturnsController(ISalesReturnService returns) => _returns = returns;

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

    /// <summary>Remaining returnable qty per line of one sales invoice (invoiced qty minus already-returned).</summary>
    [HttpGet("remaining")]
    [ProducesResponseType(typeof(IReadOnlyList<SalesInvoiceLineRemainingDto>), StatusCodes.Status200OK)]
    public async Task<ActionResult<IReadOnlyList<SalesInvoiceLineRemainingDto>>> GetRemaining([FromQuery] int salesInvoiceId, CancellationToken ct)
        => Ok(await _returns.GetRemainingByInvoiceAsync(salesInvoiceId, ct));

    /// <summary>Get one return with its lines and the ledger entries it posted.</summary>
    [HttpGet("{returnId:int}")]
    [ProducesResponseType(typeof(SalesReturnDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<ActionResult<SalesReturnDto>> 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 (inbound movement).</summary>
    [HttpPost]
    [ProducesResponseType(typeof(SalesReturnDto), StatusCodes.Status201Created)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)]
    public async Task<ActionResult<SalesReturnDto>> Create([FromBody] CreateSalesReturnRequest request, CancellationToken ct)
    {
        var dto = await _returns.CreateAsync(request, ct);
        return Created($"/api/v1/sales-returns/{dto.ReturnId}", dto);
    }
}
