todo esto funciona
# Step 1: Connect to Azure and set the subscription context
Connect-AzAccount -Subscription Eng_Dublin

# Define the Azure Key Vault URL
$akvUrl = "https://acc-insights-canprd-kv.vault.azure.net/"

# Function to retrieve secrets from Azure Key Vault with error handling
function Get-SecretFromAKV {
    param (
        [string]$secretName
    )
    try {
        $secret = Invoke-RestMethod -Uri "$akvUrl/secrets/$secretName/?api-version=7.0" -Method Get -Headers @{ "Authorization" = "Bearer $token" }
        return $secret.value
    } catch {
        Write-Error "Failed to retrieve secret ${secretName}: $($_.Exception.Message)"
    }
}

# Step 2: Retrieve secrets needed for authentication
$SdevAKV = "mmAKVdev"
$tenantId = Get-AzKeyVaultSecret -VaultName $SdevAKV -Name "PBI-TenantId" -AsPlainText
$clientId = Get-AzKeyVaultSecret -VaultName $SdevAKV -Name "PBI-AppID" -AsPlainText
$clientSecret = Get-AzKeyVaultSecret -VaultName $SdevAKV -Name "PBI-AppSecret" -AsPlainText

# Ensure token is correctly fetched for using the Key Vault
$token = az account get-access-token --resource https://vault.azure.net --query accessToken -o tsv

# Step 3: Acquire an Azure AD Access Token for Power BI
$authUrl = "https://login.microsoftonline.com/$tenantId/oauth2/token"
$body = @{
    grant_type    = "client_credentials"
    resource      = "https://analysis.windows.net/powerbi/api"
    client_id     = $clientId
    client_secret = $clientSecret
}

try {
    $response = Invoke-RestMethod -Method Post -Uri $authUrl -ContentType "application/x-www-form-urlencoded" -Body $body
    $accessToken = $response.access_token
    Write-Output "Successfully acquired Power BI access token."
} catch {
    Write-Error "Failed to acquire Power BI token: $_.Exception.Message"
    return
}

# Check Access Token
if (-not $accessToken) {
    Write-Error "Access token retrieval failed or expired."
    return
} else {
    Write-Output "Access token is valid."
}

# Define API Base URL and Required IDs
$apiBaseUrl = "https://api.powerbi.com/v1.0/myorg/groups/"
$workspaceId = "c53bc7f1-ff5c-44ff-901f-3858089aaa17"
$caNonProdCapacityId = "0D8C5E3B-E86B-4182-B5E4-E4FE83C9BDED"
$p1CapacityId = "4F327CC4-4A3B-456B-BCCB-C0ED6E2B739C"  # Updated Capacity ID
$userEmail = "ihand@accela.com"

# Updated function to handle API calls for Power BI
function Invoke-Api {
    param (
        [string]$method,
        [string]$url,
        [hashtable]$body = $null
    )

    $headers = @{ "Authorization" = "Bearer $accessToken" }
    try {
        # Convert the body to JSON only if it's in hashtable form
        if ($body -is [System.Collections.Hashtable]) {
            $bodyJson = $body | ConvertTo-Json -Compress
        } else {
            $bodyJson = $body
        }

        Write-Output "API call to: $url with method: $method"
        Write-Output "Request Body: $bodyJson"

        $response = Invoke-RestMethod -Method $method -Uri $url -Headers $headers -Body $bodyJson -ContentType "application/json"
        return $response
    } catch {
        Write-Error "API call to $url failed: $_.Exception.Message"
        return $null
    }
}

# Collect and process responses for export
$responses = @()

# Step 4: Assign the workspace to CA nonprod capacity
$assignCapacityUrl = "$apiBaseUrl$workspaceId/AssignToCapacity"
try {
    $body = @{ capacityId = $caNonProdCapacityId }
    $assignToNonProd = Invoke-Api -method "POST" -url $assignCapacityUrl -body $body
    $responses += [pscustomobject]@{ Step = "Assigned to CA nonprod capacity"; Response = $assignToNonProd }
} catch {
    Write-Error "Failed to assign to CA nonprod capacity: $_"
}

# Step 5: Assign the workspace back to P1 capacity
try {
    $body = @{ capacityId = $p1CapacityId }
    $assignToP1 = Invoke-Api -method "POST" -url $assignCapacityUrl -body $body
    $responses += [pscustomobject]@{ Step = "Assigned to P1 capacity"; Response = $assignToP1 }
} catch {
    Write-Error "Failed to assign to P1 capacity: $_"
}

# Step 6: Add a user to the workspace as Viewer
# Function to check if a user already exists in the workspace
function CheckUserExists {
    param (
        [string]$url,
        [string]$email
    )
    try {
        $response = Invoke-Api -method "GET" -url $url
        $existingUsers = $response.value
        foreach ($user in $existingUsers) {
            if ($user.emailAddress -eq $email) {
                return $true
            }
        }
        return $false
    } catch {
        Write-Error "Failed to retrieve current users: $_"
        return $false
    }
}

$addUserUrl = "$apiBaseUrl$workspaceId/users"
$checkUserUrl = "$addUserUrl"
$existCheck = CheckUserExists -url $checkUserUrl -email $userEmail

if (-not $existCheck) {
    try {
        $body = @{
            emailAddress = $userEmail
            groupUserAccessRight = "Viewer"
        }

        Write-Output "Attempting to assign user: $userEmail with role: Viewer"
        $addUser = Invoke-Api -method "POST" -url $addUserUrl -body $body
        $responses += [pscustomobject]@{ Step = "Added user as Viewer"; Response = $addUser }
    } catch {
        Write-Error "Failed to add user to workspace: $_"
    }
} else {
    Write-Output "User $userEmail is already a member of the workspace."
}

#CSV formatted for export
try {
    $formattedResponses = $responses | ForEach-Object {
        # Determine status and response text based on the Response property
        $status = if ($_.Response) { "Success" } else { "Failed" }
        $responseText = if ($_.Response) { $_.Response | Out-String } else { "No response" }
        
        # Create a custom object using the determined values
        [pscustomobject]@{
            Step     = $_.Step
            Status   = $status
            Response = $responseText
        }
    }

    # Export the formatted objects to a CSV file
    $formattedResponses | Export-Csv -Path $csvPath -NoTypeInformation
    Write-Output "Responses successfully saved to $csvPath"
} catch {
    Write-Error "Failed to export responses to CSV: $_"
}