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

namespace Books.Api.Domain.UserAccess;

public class UserCompanyAccessId(string value) : Identity<UserCompanyAccessId>(value)
{
    /// <summary>
    /// Creates a deterministic ID based on user and company.
    /// This ensures only one access record per user per company.
    /// </summary>
    public static UserCompanyAccessId FromUserAndCompany(string userId, string companyId)
    {
        var input = $"{userId}:{companyId}";
        var hash = SHA256.HashData(Encoding.UTF8.GetBytes(input));
        var guidBytes = new byte[16];
        Array.Copy(hash, guidBytes, 16);

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

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