using ZB.MOM.WW.Auth.Abstractions.Roles;

namespace ZB.MOM.WW.ScadaBridge.Security;

/// <summary>
/// Adapts ScadaBridge's DB-backed <see cref="RoleMapper"/> to the shared
/// <see cref="IGroupRoleMapper{TRole}"/> seam from <c>ZB.MOM.WW.Auth.Abstractions</c>.
/// </summary>
/// <remarks>
/// This is an <b>additive</b> wrapper for the Auth-library adoption. It does not
/// re-implement the LDAP-group → role resolution or the site-scope union semantics — it
/// delegates wholesale to <see cref="RoleMapper.MapGroupsToRolesAsync"/> and re-shapes the
/// result onto the shared contract. <typeparamref name="TRole"/> is <see cref="string"/>
/// because ScadaBridge roles travel as plain strings in claims. The full
/// <see cref="RoleMappingResult"/> — including <see cref="RoleMappingResult.PermittedSiteIds"/>
/// and <see cref="RoleMappingResult.IsSystemWideDeployment"/> — is carried verbatim in the
/// mapping's opaque <see cref="GroupRoleMapping{TRole}.Scope"/> so no site-scope information
/// is lost across the seam. The existing login flow is rewired to consume this in a later task.
/// </remarks>
public sealed class ScadaBridgeGroupRoleMapper : IGroupRoleMapper<string>
{
    private readonly RoleMapper _roleMapper;

    /// <summary>Initializes the mapper with the wrapped <see cref="RoleMapper"/>.</summary>
    /// <param name="roleMapper">The DB-backed role mapper whose union semantics are reused.</param>
    public ScadaBridgeGroupRoleMapper(RoleMapper roleMapper)
    {
        _roleMapper = roleMapper ?? throw new ArgumentNullException(nameof(roleMapper));
    }

    /// <summary>
    /// Maps a list of LDAP/AD group names to ScadaBridge roles using the wrapped
    /// <see cref="RoleMapper"/> and returns the resulting role mapping with site-scope
    /// information carried in the opaque <c>Scope</c> field.
    /// </summary>
    /// <param name="groups">The AD/LDAP group names to resolve into roles.</param>
    /// <param name="ct">Cancellation token.</param>
    /// <returns>A task that resolves to the group-to-role mapping including permitted site identifiers.</returns>
    public async Task<GroupRoleMapping<string>> MapAsync(IReadOnlyList<string> groups, CancellationToken ct)
    {
        var result = await _roleMapper.MapGroupsToRolesAsync(groups, ct);

        // Carry the full RoleMappingResult as the opaque Scope so the site-scope
        // payload (PermittedSiteIds + IsSystemWideDeployment) survives the seam.
        return new GroupRoleMapping<string>(result.Roles, Scope: result);
    }
}
