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

namespace Books.Api.Domain.Invoices;

public class InvoiceId(string value) : Identity<InvoiceId>(value)
{
    /// <summary>
    /// Creates a deterministic InvoiceId based on company, year, and invoice number.
    /// This ensures idempotency and prevents duplicate invoices.
    /// Momsloven §52 requires sequential numbering per year.
    /// </summary>
    public static InvoiceId FromCompanyYearAndNumber(string companyId, int year, string invoiceNumber)
    {
        var input = $"{companyId}:invoice:{year}:{invoiceNumber}";
        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 InvoiceId($"invoice-{deterministicGuid:D}");
    }

}
