using Microsoft.Extensions.Options;
using ZB.MOM.WW.Auth.Abstractions.Roles;
using ZB.MOM.WW.OtOpcUa.Configuration.Services;

namespace ZB.MOM.WW.OtOpcUa.Security.Ldap;

/// <summary>
///     OtOpcUa's <see cref="IGroupRoleMapper{TRole}"/> implementation (roles are plain strings,
///     so <c>TRole = string</c>). A thin, behaviour-preserving adapter over the existing
///     <see cref="RoleMapper"/>: it computes the appsettings baseline via
///     <see cref="RoleMapper.Map"/>, then unions in system-wide DB grants via
///     <see cref="RoleMapper.Merge"/>. The OtOpcUa authz model is global (no per-cluster scope at
///     login), so <see cref="GroupRoleMapping{TRole}.Scope"/> is always <c>null</c>.
/// </summary>
/// <remarks>
///     This is the shared-library seam introduced ahead of rewiring the login flow; it does not
///     duplicate mapping logic and does not change behaviour. See <c>scadaproj/components/auth</c>.
/// </remarks>
public sealed class OtOpcUaGroupRoleMapper(
    IOptions<LdapOptions> ldapOptions,
    ILdapGroupRoleMappingService dbMappings) : IGroupRoleMapper<string>
{
    /// <summary>Maps a user's LDAP group memberships to their OtOpcUa roles.</summary>
    /// <param name="groups">The LDAP group names the user is a member of.</param>
    /// <param name="ct">Cancellation token for the DB lookup.</param>
    /// <returns>
    ///     The merged role mapping — the appsettings <c>GroupToRole</c> baseline unioned with
    ///     any matching system-wide DB grants, with a <c>null</c> <see cref="GroupRoleMapping{TRole}.Scope"/>.
    /// </returns>
    public async Task<GroupRoleMapping<string>> MapAsync(IReadOnlyList<string> groups, CancellationToken ct)
    {
        ArgumentNullException.ThrowIfNull(groups);

        var baseline = RoleMapper.Map(groups, ldapOptions.Value.GroupToRole);
        var dbRows = await dbMappings.GetByGroupsAsync(groups, ct).ConfigureAwait(false);
        var merged = RoleMapper.Merge(baseline, dbRows);

        return new GroupRoleMapping<string>(merged, Scope: null);
    }
}
