using Microsoft.Online.SharePoint.TenantAdministration;
using Microsoft.SharePoint.Client;

namespace SharepointToolbox.Services;

public class OwnershipElevationService : IOwnershipElevationService
{
    public async Task ElevateAsync(ClientContext tenantAdminCtx, string siteUrl, string loginName, CancellationToken ct)
    {
        // Tenant.SetSiteAdmin requires a real claims/UPN login; an empty string
        // makes the server raise "Cannot convert Org ID to Claims" and abort.
        // When the caller doesn't specify a user, fall back to the signed-in
        // admin (the owner of tenantAdminCtx).
        if (string.IsNullOrWhiteSpace(loginName))
        {
            tenantAdminCtx.Load(tenantAdminCtx.Web.CurrentUser, u => u.LoginName);
            await tenantAdminCtx.ExecuteQueryAsync();
            loginName = tenantAdminCtx.Web.CurrentUser.LoginName;
        }

        var tenant = new Tenant(tenantAdminCtx);
        tenant.SetSiteAdmin(siteUrl, loginName, isSiteAdmin: true);
        await tenantAdminCtx.ExecuteQueryAsync();
    }
}
