
# FortuneBetAPI.ps1

# Global state
$Global:FortuneBetToken = $null
$Global:FortuneBetRefreshToken = $null
$Global:ApiBase = "http://127.0.0.1:8080/api/v1"
$Global:TenantSlug = "fortunebets"   # adjust if different

function Invoke-FortuneBetRequest {
    param(
        [string]$Method,
        [string]$Path,
        [object]$Body = $null,
        [switch]$Tenant
    )

    $url = if ($Tenant) {
        "$Global:ApiBase/tenant/$Global:TenantSlug/$Path"
    } else {
        "$Global:ApiBase/$Path"
    }

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

    if ($Global:FortuneBetToken) {
        $headers["Authorization"] = "Bearer $($Global:FortuneBetToken)"
    }

    $bodyJson = if ($Body) { ($Body | ConvertTo-Json -Depth 5 -Compress) } else { $null }

    try {
        $response = Invoke-RestMethod -Method $Method -Uri $url -Headers $headers -Body $bodyJson
        return $response
    }
    catch {
        Write-Error "Request failed: $($_.Exception.Message)"
        if ($_.ErrorDetails) { Write-Host $_.ErrorDetails }
    }
}

function Login-FortuneBetCustomer {
    param(
        [string]$Email,
        [string]$Password
    )

    $payload = @{
        email    = $Email
        password = $Password
    }

    $resp = Invoke-FortuneBetRequest -Method "POST" -Path "auth/customer-login" -Tenant -Body $payload
    if ($resp -and $resp.access_token) {
        $Global:FortuneBetToken = $resp.access_token
        $Global:FortuneBetRefreshToken = $resp.refresh_token
        Write-Host "✅ Logged in. Token stored."
    } else {
        Write-Error "❌ Login failed. Response: $($resp | ConvertTo-Json -Depth 5)"
    }
}

function Refresh-FortuneBetToken {
    if (-not $Global:FortuneBetRefreshToken) {
        Write-Error "No refresh token stored."
        return
    }

    $payload = @{
        refresh_token = $Global:FortuneBetRefreshToken
    }

    $resp = Invoke-FortuneBetRequest -Method "POST" -Path "auth/refresh" -Body $payload
    if ($resp -and $resp.access_token) {
        $Global:FortuneBetToken = $resp.access_token
        Write-Host "🔄 Token refreshed."
    } else {
        Write-Error "❌ Refresh failed."
    }
}

# Example convenience wrapper
function Get-FortuneBetProfile {
    $resp = Invoke-FortuneBetRequest -Method "GET" -Path "user/customer-profile" -Tenant
    return $resp
}

# Example usage:
# . .\FortuneBetAPI.ps1     # dot-source to load functions
# Login-FortuneBetCustomer -Email "test@example.com" -Password "1234"
# Get-FortuneBetProfile
# Refresh-FortuneBetToken
