CairoVolt.WooCommerce.psm1

<#
.Synopsis
    PowerShell tools for WooCommerce store management and analysis, originally built for CairoVolt.
.Description
    A lightweight, functional PowerShell helper module to query, analyze, and verify product
    catalog state and order telemetry from WooCommerce REST APIs.
#>


function Connect-WooCommerce {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$StoreUrl,

        [Parameter(Mandatory = $true)]
        [string]$ConsumerKey,

        [Parameter(Mandatory = $true)]
        [string]$ConsumerSecret
    )

    process {
        # Construct authentication header
        $encodedCreds = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("${ConsumerKey}:${ConsumerSecret}"))
        $authHeader = @{ Authorization = "Basic $encodedCreds" }

        # Store session in global variable
        $global:WooCommerceSession = @{
            StoreUrl   = $StoreUrl.TrimEnd('/')
            AuthHeader = $authHeader
        }

        Write-Verbose "Successfully established WooCommerce connection credentials for $StoreUrl."
        return $global:WooCommerceSession
    }
}

function Get-WooProduct {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false)]
        [string]$Category,

        [Parameter(Mandatory = $false)]
        [int]$Limit = 50
    )

    process {
        if (-not $global:WooCommerceSession) {
            Throw "No active WooCommerce session found. Run 'Connect-WooCommerce' first."
        }

        $apiUrl = "$($global:WooCommerceSession.StoreUrl)/wp-json/wc/v3/products?per_page=$Limit"
        if ($Category) {
            $apiUrl += "&category=$Category"
        }

        Write-Verbose "Fetching products from $apiUrl..."
        try {
            $products = Invoke-RestMethod -Uri $apiUrl -Method Get -Headers $global:WooCommerceSession.AuthHeader -ErrorAction Stop
            return $products
        }
        catch {
            Write-Error "Failed to fetch products: $_"
        }
    }
}

function Get-WooOrder {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false)]
        [string]$Status,

        [Parameter(Mandatory = $false)]
        [int]$Limit = 50
    )

    process {
        if (-not $global:WooCommerceSession) {
            Throw "No active WooCommerce session found. Run 'Connect-WooCommerce' first."
        }

        $apiUrl = "$($global:WooCommerceSession.StoreUrl)/wp-json/wc/v3/orders?per_page=$Limit"
        if ($Status) {
            $apiUrl += "&status=$Status"
        }

        Write-Verbose "Fetching orders from $apiUrl..."
        try {
            $orders = Invoke-RestMethod -Uri $apiUrl -Method Get -Headers $global:WooCommerceSession.AuthHeader -ErrorAction Stop
            return $orders
        }
        catch {
            Write-Error "Failed to fetch orders: $_"
        }
    }
}

Export-ModuleMember -Function Connect-WooCommerce, Get-WooProduct, Get-WooOrder