using System.Security.Cryptography;
using System.Text;
using EventFlow.Core;

namespace Books.Api.Domain.Products;

public class ProductId(string value) : Identity<ProductId>(value)
{
    /// <summary>
    /// Creates a deterministic ProductId based on company and product number.
    /// This prevents duplicate products even with race conditions.
    /// Uses SHA256 to generate a deterministic GUID from the input.
    /// </summary>
    public static ProductId FromCompanyAndNumber(string companyId, string productNumber)
    {
        var input = $"{companyId}:product:{productNumber}";
        var hash = SHA256.HashData(Encoding.UTF8.GetBytes(input));

        var guidBytes = new byte[16];
        Array.Copy(hash, guidBytes, 16);

        // Set version (4) and variant bits to make it a valid UUID
        guidBytes[6] = (byte)((guidBytes[6] & 0x0F) | 0x40);
        guidBytes[8] = (byte)((guidBytes[8] & 0x3F) | 0x80);

        var deterministicGuid = new Guid(guidBytes);
        return new ProductId($"product-{deterministicGuid:D}");
    }
}
