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

namespace Books.Api.Domain.Orders;

public class OrderId(string value) : Identity<OrderId>(value)
{
    /// <summary>
    /// Creates a deterministic OrderId based on company, year, and order number.
    /// This ensures idempotency and prevents duplicate orders.
    /// </summary>
    public static OrderId FromCompanyYearAndNumber(string companyId, int year, string orderNumber)
    {
        var input = $"{companyId}:order:{year}:{orderNumber}";
        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 OrderId($"order-{deterministicGuid:D}");
    }
}
