# CIPP - Add Claude-MSP-Access as Auto-Consent App Template
# This adds Claude's app to CIPP so it gets automatically consented
# when you add new tenants via CIPP.
#
# Uses the CIPP API (ClaudeCipp2 credentials)

$ErrorActionPreference = "Stop"

$cippUrl = "https://cippcanvb.azurewebsites.net"
$cippTenantId = "ce61461e-81a0-4c84-bb4a-7b354a9a356d"
$cippClientId = "420cb849-542d-4374-9cb2-3d8ae0e1835b"
$cippClientSecret = "MOn8Q~otmxJPLvmL~_aCVTV8Va4t4~SrYrukGbJT"
$cippScope = "api://420cb849-542d-4374-9cb2-3d8ae0e1835b/.default"

$claudeAppId = "fabb3421-8b34-484b-bc17-e46de9703418"

Write-Output "========================================="
Write-Output " CIPP - Add Claude-MSP-Access Template"
Write-Output " $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
Write-Output "========================================="

# --- STEP 1: Get CIPP API token ---
Write-Output "`n[STEP 1] Getting CIPP API token..."
$tokenBody = @{
    client_id     = $cippClientId
    client_secret = $cippClientSecret
    scope         = $cippScope
    grant_type    = "client_credentials"
}
$tokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$cippTenantId/oauth2/v2.0/token" -Method POST -Body $tokenBody
$token = $tokenResponse.access_token
Write-Output "[OK] Got CIPP API token"

$headers = @{
    "Authorization" = "Bearer $token"
    "Content-Type"  = "application/json"
}

# --- STEP 2: Check existing app approval templates ---
Write-Output "`n[STEP 2] Checking existing app approval templates..."
try {
    $existing = Invoke-RestMethod -Uri "$cippUrl/api/ExecAppPermissionTemplate" -Headers $headers -Method GET
    Write-Output "[INFO] Found $($existing.Count) existing template(s)"
    foreach ($tmpl in $existing) {
        Write-Output "  - $($tmpl.displayName) ($($tmpl.appId))"
    }
} catch {
    Write-Output "[INFO] No existing templates or endpoint returned error: $($_.Exception.Message)"
}

# --- STEP 3: Add Claude-MSP-Access as app template ---
Write-Output "`n[STEP 3] Adding Claude-MSP-Access app template..."

# Application permissions Claude needs consented in each customer tenant
$appPermissions = @(
    "User.ReadWrite.All",
    "Directory.ReadWrite.All",
    "Mail.ReadWrite",
    "MailboxSettings.ReadWrite",
    "AuditLog.Read.All",
    "Application.ReadWrite.All",
    "DelegatedPermissionGrant.ReadWrite.All",
    "Group.ReadWrite.All",
    "GroupMember.ReadWrite.All",
    "SecurityEvents.ReadWrite.All",
    "SecurityEvents.Read.All",
    "SecurityIncident.ReadWrite.All",
    "AppRoleAssignment.ReadWrite.All",
    "UserAuthenticationMethod.ReadWrite.All",
    "Organization.ReadWrite.All",
    "Domain.Read.All",
    "Policy.Read.All",
    "Policy.ReadWrite.ConditionalAccess",
    "Policy.ReadWrite.AuthenticationMethod",
    "Policy.ReadWrite.AuthenticationFlows",
    "Policy.ReadWrite.ApplicationConfiguration",
    "Policy.ReadWrite.ConsentRequest",
    "Policy.ReadWrite.CrossTenantAccess",
    "Reports.Read.All",
    "ReportSettings.ReadWrite.All",
    "Device.ReadWrite.All",
    "DeviceManagementApps.ReadWrite.All",
    "DeviceManagementConfiguration.ReadWrite.All",
    "DeviceManagementManagedDevices.ReadWrite.All",
    "DeviceManagementManagedDevices.PrivilegedOperations.All",
    "DeviceManagementRBAC.ReadWrite.All",
    "DeviceManagementServiceConfig.ReadWrite.All",
    "CrossTenantInformation.ReadBasic.All",
    "Channel.Create",
    "Channel.ReadBasic.All",
    "ChannelMember.ReadWrite.All",
    "Files.ReadWrite.All",
    "Group.Create",
    "InformationProtectionPolicy.Read.All",
    "Place.Read.All",
    "PrivilegedAccess.ReadWrite.AzureADGroup",
    "SharePointTenantSettings.ReadWrite.All",
    "Sites.FullControl.All",
    "TeamMember.ReadWrite.All",
    "TeamMember.ReadWriteNonOwnerRole.All",
    "TeamsTelephoneNumber.ReadWrite.All"
)

$templateBody = @{
    AppId       = $claudeAppId
    displayName = "Claude-MSP-Access (AI Investigation & Remediation)"
    Permissions = $appPermissions
} | ConvertTo-Json -Depth 5

try {
    $result = Invoke-RestMethod -Uri "$cippUrl/api/ExecAppPermissionTemplate" -Headers $headers -Method POST -Body $templateBody
    Write-Output "[OK] Template added: $($result | ConvertTo-Json -Compress)"
} catch {
    $errBody = $_.ErrorDetails.Message
    Write-Output "[WARNING] API response: $errBody"
    Write-Output "[INFO] If the endpoint doesn't support POST, you can add the template manually:"
    Write-Output "  CIPP > Settings > Application Approval > Add Application"
    Write-Output "  App ID: $claudeAppId"
    Write-Output "  Name: Claude-MSP-Access (AI Investigation & Remediation)"
    Write-Output ""
    Write-Output "Or use the CIPP UI to navigate to:"
    Write-Output "  Tenant Administration > Application Approval"
    Write-Output "  Click 'Add App' and enter the App ID above"
}

# --- STEP 4: Summary ---
Write-Output "`n========================================="
Write-Output " TEMPLATE SETUP SUMMARY"
Write-Output "========================================="
Write-Output ""
Write-Output "App ID:   $claudeAppId"
Write-Output "Name:     Claude-MSP-Access (AI Investigation & Remediation)"
Write-Output "Perms:    $($appPermissions.Count) application permissions"
Write-Output ""
Write-Output "What happens now:"
Write-Output "  1. When you add a new tenant in CIPP, Claude's app gets auto-consented"
Write-Output "  2. For existing tenants, run CPV Refresh in CIPP to push the permissions"
Write-Output "  3. The admin consent URL also works as a manual fallback:"
Write-Output ""
Write-Output "  https://login.microsoftonline.com/common/adminconsent?client_id=$claudeAppId&redirect_uri=https://login.microsoftonline.com/common/oauth2/nativeclient"
Write-Output ""
