using ERPCore.Common.Http;
using ERPCore.Infra.Auth;
using ERPCore.System.Errors;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace ERPCore.Controllers;

/// <summary>
/// Base for the v1 API controllers. Centralises ETag / If-Match handling
/// (docs/11-BACKEND-PHASE1.md §1.6) so concurrency behaviour is uniform.
/// Each controller declares its own explicit lowercase <c>[Route]</c> to match
/// the API contract paths (docs/11 §1.1). Every v1 endpoint requires a valid
/// AuthHex token satisfying the ERP door policy (docs/10 A.4).
/// </summary>
[ApiController]
[Produces("application/json")]
[Authorize(JwtAuthExtensions.ErpAccessPolicy)]
public abstract class ApiControllerBase : ControllerBase
{
    /// <summary>Parse a mandatory <c>If-Match</c> header, or 428 if absent/malformed.</summary>
    protected uint RequireIfMatch()
    {
        var header = Request.Headers.IfMatch.ToString();
        if (!ETag.TryParse(header, out var rowVersion))
            throw new DomainException("PRECONDITION_REQUIRED", "A valid If-Match header is required for this update.", 428);
        return rowVersion;
    }

    /// <summary>Emit the strong <c>ETag</c> response header for a row-version token.</summary>
    protected void SetETag(uint rowVersion) => Response.Headers.ETag = ETag.From(rowVersion);
}
