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

namespace ERPCore.Controllers;

/// <summary>Vendor master endpoints (docs/11-BACKEND-PHASE1.md §2.4).</summary>
[Route("api/v1/vendors")]
public sealed class VendorsController : ApiControllerBase
{
    private readonly IVendorService _vendors;

    public VendorsController(IVendorService vendors) => _vendors = vendors;

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

    [HttpGet("{vendorId:int}")]
    [ProducesResponseType(typeof(VendorDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<ActionResult<VendorDto>> GetById(int vendorId, CancellationToken ct)
    {
        var result = await _vendors.GetAsync(vendorId, ct);
        if (result is null) return NotFound();

        SetETag(result.RowVersion);
        return Ok(result.Value);
    }

    [HttpPost]
    [ProducesResponseType(typeof(VendorDto), StatusCodes.Status201Created)]
    [ProducesResponseType(StatusCodes.Status409Conflict)]
    public async Task<ActionResult<VendorDto>> Create([FromBody] CreateVendorRequest request, CancellationToken ct)
    {
        var result = await _vendors.CreateAsync(request, ct);
        SetETag(result.RowVersion);
        return Created($"/api/v1/vendors/{result.Value.VendorId}", result.Value);
    }

    [HttpPut("{vendorId:int}")]
    [ProducesResponseType(typeof(VendorDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    [ProducesResponseType(StatusCodes.Status412PreconditionFailed)]
    public async Task<ActionResult<VendorDto>> Update(int vendorId, [FromBody] UpdateVendorRequest request, CancellationToken ct)
    {
        var expected = RequireIfMatch();
        var result = await _vendors.UpdateAsync(vendorId, request, expected, ct);
        SetETag(result.RowVersion);
        return Ok(result.Value);
    }

    [HttpPatch("{vendorId:int}/status")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> SetStatus(int vendorId, [FromBody] UpdateVendorStatusRequest request, CancellationToken ct)
    {
        await _vendors.SetStatusAsync(vendorId, request.Status, ct);
        return NoContent();
    }
}
