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

namespace Books.Api.Domain.FiscalYears;

public class FiscalYearId : Identity<FiscalYearId>
{
    public FiscalYearId(string value) : base(value) { }

    /// <summary>
    /// Creates a deterministic FiscalYearId based on company, start date, and end date.
    /// This prevents duplicate fiscal years even with race conditions.
    /// Uses SHA256 to generate a deterministic GUID from the input.
    /// </summary>
    public static FiscalYearId FromCompanyAndDates(string companyId, DateOnly startDate, DateOnly endDate)
    {
        var input = $"{companyId}:{startDate:yyyy-MM-dd}:{endDate:yyyy-MM-dd}";
        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); // Version 4
        guidBytes[8] = (byte)((guidBytes[8] & 0x3F) | 0x80); // Variant 1

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