using BuildingBlock.Identity.Contracts.Requests;
using BuildingBlock.Identity.Contracts.Responses;
using Thalos.Domain.Contracts;

namespace Thalos.Domain.Decisions;

/// <summary>
/// Default domain implementation for identity policy decision workflows.
/// </summary>
public sealed class IdentityPolicyDecisionService : IIdentityPolicyDecisionService
{
    /// <inheritdoc />
    public IdentityPolicyContextRequest BuildPolicyContextRequest(EvaluateIdentityPolicyRequest request)
    {
        return new IdentityPolicyContextRequest(request.SubjectId, request.TenantId, request.PermissionCode);
    }

    /// <inheritdoc />
    public EvaluateIdentityPolicyResponse Evaluate(
        EvaluateIdentityPolicyRequest request,
        IdentityPolicyContextData policyContextData)
    {
        var permissionMatched = policyContextData.GrantedPermissions.Any(permission =>
            string.Equals(permission, request.PermissionCode, StringComparison.OrdinalIgnoreCase));

        return new EvaluateIdentityPolicyResponse(
            request.SubjectId,
            request.PermissionCode,
            policyContextData.ContextSatisfied && permissionMatched);
    }
}
