using ERPCore.Dtos.Config;
using ERPCore.Services.Interfaces;
using Microsoft.AspNetCore.Mvc;

namespace ERPCore.Controllers;

/// <summary>
/// Product configuration endpoints (docs/11-BACKEND-PHASE1.md §2.8) — the singleton
/// feature gate for subcategories/brands/item-types.
/// <para>
/// <b>Authorization:</b> writes are admitted by the inherited ERP door policy only.
/// A dedicated <c>CONFIG_MANAGE</c> permission is reserved for when per-endpoint RBAC
/// lands (FR-X-01, currently deferred) — at that point this action gets the attribute
/// with no other change. Until then any ERP-admitted user can flip these flags; that is
/// the accepted Phase-1 posture, consistent with every other endpoint.
/// </para>
/// </summary>
[Route("api/v1/product-config")]
public sealed class ProductConfigController : ApiControllerBase
{
    private readonly IProductConfigService _config;

    public ProductConfigController(IProductConfigService config) => _config = config;

    [HttpGet]
    [ProducesResponseType(typeof(ProductConfigDto), StatusCodes.Status200OK)]
    public async Task<ActionResult<ProductConfigDto>> Get(CancellationToken ct)
    {
        var result = await _config.GetAsync(ct);
        SetETag(result.RowVersion);
        return Ok(result.Value);
    }

    [HttpPut]
    [ProducesResponseType(typeof(ProductConfigDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    [ProducesResponseType(StatusCodes.Status412PreconditionFailed)]
    public async Task<ActionResult<ProductConfigDto>> Update(
        [FromBody] UpdateProductConfigRequest request, CancellationToken ct)
    {
        var expected = RequireIfMatch();
        var result = await _config.UpdateAsync(request, expected, ct);
        SetETag(result.RowVersion);
        return Ok(result.Value);
    }
}
