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

namespace ERPCore.Controllers;

/// <summary>Stock-count endpoints (docs/11 §5.6).</summary>
[Route("api/v1/stock-counts")]
public sealed class StockCountsController : ApiControllerBase
{
    private readonly ICountService _counts;

    public StockCountsController(ICountService counts) => _counts = counts;

    /// <summary>List counts, newest first.</summary>
    [HttpGet]
    [ProducesResponseType(typeof(PagedResponse<CountSummaryDto>), StatusCodes.Status200OK)]
    public async Task<ActionResult<PagedResponse<CountSummaryDto>>> List(
        [FromQuery] PageQuery query, [FromQuery] CountStatus? status, [FromQuery] int? warehouseId, CancellationToken ct)
        => Ok(await _counts.ListAsync(query, status, warehouseId, ct));

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

    /// <summary>Create a count with system quantities snapshotted (immutable).</summary>
    [HttpPost]
    [ProducesResponseType(typeof(CountDto), StatusCodes.Status201Created)]
    [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)]
    public async Task<ActionResult<CountDto>> Create([FromBody] CreateCountRequest request, CancellationToken ct)
    {
        var dto = await _counts.CreateAsync(request, ct);
        return Created($"/api/v1/stock-counts/{dto.CountId}", dto);
    }

    /// <summary>Enter counted quantities; variance = counted − system.</summary>
    [HttpPut("{countId:int}/counts")]
    [ProducesResponseType(typeof(CountDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    [ProducesResponseType(StatusCodes.Status409Conflict)]
    public async Task<ActionResult<CountDto>> EnterCounts(int countId, [FromBody] EnterCountsRequest request, CancellationToken ct)
        => Ok(await _counts.EnterCountsAsync(countId, request, ct));

    /// <summary>Post: emit a variance adjustment and close the count.</summary>
    [HttpPost("{countId:int}/post")]
    [ProducesResponseType(typeof(CountPostResultDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    [ProducesResponseType(StatusCodes.Status409Conflict)]
    public async Task<ActionResult<CountPostResultDto>> Post(int countId, CancellationToken ct)
        => Ok(await _counts.PostAsync(countId, ct));
}
