$subscriptionId = "8e2a4b60-40b1-422b-8275-7a02e8b951db"  
Connect-AzAccount -SubscriptionId $subscriptionId

# Configuración de Key Vault y otras variables
$vaultName = "mmAKVdev"
$pbiWorkspaceId = "c53bc7f1-ff5c-44ff-901f-3858089aaa17"
$pbiDatasetId = "99067349-8999-4869-9569-ed4c4aa1a7ef"
$refreshCapacityId = "43D1E91C-FEF3-4B37-98CF-3F31E396803B"
$renderCapacityId = "4F327CC4-4A3B-456B-BCCB-C0ED6E2B739C"
$newUserEmail = "ihand@accela.com"

# Función para obtener un secreto de Azure Key Vault
function Get-SecretFromKeyVault {
    param(
        [string]$vaultName,
        [string]$secretName
    )
    try {
        $secret = Get-AzKeyVaultSecret -VaultName $vaultName -Name $secretName
        return $secret.SecretValueText
    } catch {
        Write-Error "Error retrieving secret $secretName from Key Vault: $($_.Exception.Message)"
        return $null
    }
}

# Obtener tenantId, clientId y clientSecret del Key Vault
$tenantId = dg_prod_azure_admin_ops_accela
$clientId = Get-SecretFromKeyVault -vaultName $vaultName -secretName "PBI-AppID"
$clientSecret = Get-SecretFromKeyVault -vaultName $vaultName -secretName "PBI-AppSecret"

if (-not $tenantId -or -not $clientId -or -not $clientSecret) {
    Write-Error "Failed to retrieve necessary credentials from Key Vault."
    return
}

# Función para obtener un token de acceso desde Azure AD
function Get-AADToken {
    $tokenUrl = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
    $body = @{
        grant_type    = "client_credentials"
        scope         = "https://analysis.windows.net/powerbi/api/.default"
        client_id     = $clientId
        client_secret = $clientSecret
    }
    try {
        $response = Invoke-RestMethod -Method Post -Uri $tokenUrl -ContentType "application/x-www-form-urlencoded" -Body $body
        return $response.access_token
    } catch {
        Write-Error "Failed to obtain access token: $($_.Exception.Message)"
        return $null
    }
}

# Obtener el token de acceso
$accessToken = Get-AADToken

if (-not $accessToken) {
    Write-Error "Access token was not retrieved, terminating script execution."
    return
}

# Configuración de headers de autenticación
$headers = @{
    Authorization = "Bearer $accessToken"
    "Content-Type" = "application/json"
}

# Funciones para operaciones de Power BI

function AssignWorkspaceToCapacity {
    param (
        [string]$workspaceId,
        [string]$capacityId
    )
    try {
        $body = @{ capacityId = $capacityId } | ConvertTo-Json
        $response = Invoke-RestMethod -Method Post -Uri "https://api.powerbi.com/v1.0/myorg/groups/$workspaceId/AssignToCapacity" -Headers $headers -Body $body
        Write-Output "Workspace $workspaceId assigned to capacity ${capacityId}."
    } catch {
        Write-Error "Failed to move Workspace $workspaceId to capacity ${capacityId}: $($_.Exception.Message)"
    }
}

function GetWorkspaceInfo {
    param (
        [string]$workspaceId
    )
    try {
        $response = Invoke-RestMethod -Method Get -Uri "https://api.powerbi.com/v1.0/myorg/groups/$workspaceId" -Headers $headers
        return $response
    } catch {
        Write-Error "Failed to get workspace information: $($_.Exception.Message)"
        return $null
    }
}

function GetDatasetInfo {
    param (
        [string]$workspaceId,
        [string]$datasetId
    )
    try {
        $response = Invoke-RestMethod -Method Get -Uri "https://api.powerbi.com/v1.0/myorg/groups/$workspaceId/datasets/$datasetId" -Headers $headers
        return $response
    } catch {
        Write-Error "Failed to get dataset information: $($_.Exception.Message)"
        return $null
    }
}

function AddUserToWorkspace {
    param (
        [string]$workspaceId,
        [string]$email
    )
    try {
        $body = @{
            groupUserAccessRight = "Viewer"
            emailAddress = $email
        } | ConvertTo-Json
        Invoke-RestMethod -Method Post -Uri "https://api.powerbi.com/v1.0/myorg/groups/$workspaceId/users" -Headers $headers -Body $body
        Write-Output "User $email added as Viewer to the workspace $workspaceId."
    } catch {
        Write-Error "Failed to add user to the workspace $workspaceId: $($_.Exception.Message)"
    }
}

function GetLastRefreshStatus {
    param (
        [string]$workspaceId,
        [string]$datasetId
    )
    try {
        $response = Invoke-RestMethod -Method Get -Uri "https://api.powerbi.com/v1.0/myorg/groups/$workspaceId/datasets/$datasetId/refreshes?$top=1" -Headers $headers
        return $response.value[0]
    } catch {
        Write-Error "Failed to get last refresh status: $($_.Exception.Message)"
        return $null
    }
}

# Ejecutar funciones

AssignWorkspaceToCapacity -workspaceId $pbiWorkspaceId -capacityId $refreshCapacityId
$workspaceInfo = GetWorkspaceInfo -workspaceId $pbiWorkspaceId
$datasetInfo = GetDatasetInfo -workspaceId $pbiWorkspaceId -datasetId $pbiDatasetId
AddUserToWorkspace -workspaceId $pbiWorkspaceId -email $newUserEmail
$lastRefreshStatus = GetLastRefreshStatus -workspaceId $pbiWorkspaceId -datasetId $pbiDatasetId
AssignWorkspaceToCapacity -workspaceId $pbiWorkspaceId -capacityId $renderCapacityId

# Guardar las respuestas en un archivo JSON
$documentsPath = [environment]::GetFolderPath('MyDocuments')
$output = @($workspaceInfo, $datasetInfo, $lastRefreshStatus)
$output | ConvertTo-Json | Out-File -FilePath 

Write-Output 

At line:126 char:58
+ ... rite-Error "Failed to add user to the workspace $workspaceId: $($_.Ex ...
+                                                     ~~~~~~~~~~~~~
Variable reference is not valid. ':' was not followed by a valid variable name character. Consider using ${} to
delimit the name.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : InvalidVariableReferenceWithDrive