# 1. Connect to the Azure account and set the subscription context
Connect-AzAccount -Subscription Eng_Dublin
$SdevAKV = "mmAKVdev"

# 2. Retrieve secrets from the development Key Vault
$SdevAppId = Get-AzKeyVaultSecret -VaultName $SdevAKV -Name "PBI-APPID" -AsPlainText

# Set the context to the shared services subscription
Set-AzContext -Subscription civp_mt_shared_services
$ScanonprodAKV = "acc-insights-canprd-kv"

# Retrieve secrets from the non-production Key Vault
$SnonprodAppId = Get-AzKeyVaultSecret -VaultName $ScanonprodAKV -Name "PBI-APPID" -AsPlainText

# 3. Get the access token for Azure Key Vault in development
$token = az account get-access-token --resource https://vault.azure.net --query accessToken -o tsv  # AKV Eng_Dublin

# 4. Function to get secrets from Azure Key Vault
function Get-SecretFromAKV {
    param (
        [string]$secretName
    )
    $secret = Invoke-RestMethod -Uri "$akvUrl/secrets/$secretName/?api-version=7.0" -Method Get -Headers @{ "Authorization" = "Bearer $token" }
    return $secret.value
}

# 5. Define URLs and get secrets
$akvUrl = "https://acc-insights-canprd-kv.vault.azure.net/"
$tenantId = Get-SecretFromAKV -secretName "PBI-TenantId"
$clientId = Get-SecretFromAKV -secretName "PBI-AppID"
$clientSecret = Get-SecretFromAKV -secretName "PBI-AppSecret"

# Print Token Values
Write-Output "Tenant ID: $tenantId"
Write-Output "Client ID: $clientId"
Write-Output "Client Secret: $clientSecret"

# Get the Power BI token
$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
}

$response = Invoke-RestMethod -Method Post -Uri $authUrl -ContentType "application/x-www-form-urlencoded" -Body $body
$token = $response.access_token

# Define API URLs and necessary IDs
$apiBaseUrl = "https://api.powerbi.com/v1.0/myorg/groups/"
$workspaceId = "c53bc7f1-ff5c-44ff-901f-3858089aaa17"
$caNonProdCapacityId = "0D8C5E3B-E86B-4182-B5E4-E4FE83C9BDED"  # CANPRd
$p1CapacityId = "99A993F1-4D84-4B6C-AAB7-85286F38E239"  # p1
$userEmail = "ihand@accela.com"

# Function to invoke the API and return the response
function Invoke-Api {
    param (
        [string]$method,
        [string]$url,
        [hashtable]$body = $null
    )
    try {
        $response = Invoke-RestMethod -Method $method -Uri $url -Headers @{ "Authorization" = "Bearer $token" } -Body ($body | ConvertTo-Json)
        return $response
    } catch {
        Write-Error "Error invocando la API: $_"
        throw $_
    }
}

# Initialize an array to store responses
$responses = @()

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

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

# 3. Get the workspace information
try {
    $workspaceInfoUrl = "$apiBaseUrl$workspaceId"
    $workspaceInfo = Invoke-Api -method "GET" -url $workspaceInfoUrl
    $responses += [pscustomobject]@{ Step = "Get workspace information"; Response = $workspaceInfo }
} catch {
    Write-Error "Failed to get workspace information: $_"
}

# 4. Get the dataset information
try {
    $datasetInfoUrl = "$apiBaseUrl$workspaceId/datasets"
    $datasetInfo = Invoke-Api -method "GET" -url $datasetInfoUrl
    $responses += [pscustomobject]@{ Step = "Get dataset information"; Response = $datasetInfo }
} catch {
    Write-Error "Failed to get dataset information: $_"
}

# 5. Add a user to the workspace as Viewer
try {
    $addUserUrl = "$apiBaseUrl$workspaceId/users"
    $body = @{
        emailAddress = $userEmail
        groupUserAccessRight = "Viewer"
    }
    $addUser = Invoke-Api -method "POST" -url $addUserUrl -body $body
    $responses += [pscustomobject]@{ Step = "Add user to workspace"; Response = $addUser }
} catch {
    Write-Error "Failed to add user to workspace: $_"
}

# 6. Get the gateway ID
try {
    $gatewayUrl = "https://api.powerbi.com/v1.0/myorg/gateways"
    $gatewayInfo = Invoke-Api -method "GET" -url $gatewayUrl
    $gatewayIds = $gatewayInfo.value | ForEach-Object { $_.id }
    $responses += [pscustomobject]@{ Step = "Get gateway ID"; Response = ($gatewayIds -join ", ") }
} catch {
    Write-Error "Failed to get gateway ID: $_"
}

# 7. Get the last refresh status
try {
    $refreshStatusUrl = "$apiBaseUrl$workspaceId/datasets/{datasetId}/refreshes?$top=1"
    $refreshStatus = Invoke-Api -method "GET" -url $refreshStatusUrl
    $lastRefreshStatus = $refreshStatus.value | Select-Object -First 1
    $responses += [pscustomobject]@{ Step = "Get last refresh status"; Response = $lastRefreshStatus }
} catch {
    Write-Error "Failed to get last refresh status: $_"
}

# Export the responses to a CSV file in the Documents folder
$csvPath = [System.IO.Path]::Combine([System.Environment]::GetFolderPath('MyDocuments'), "responses.csv")
$responses | Export-Csv -Path $csvPath -NoTypeInformation

Write-Output "Responses saved to $csvPath"