# RescuePC Protected Module - DO NOT EDIT
# Source code is maintained separately in the development repository.

$script:LicenseCachePath = "$env:ProgramData\RescuePC\license_cache.json"
$script:LicenseCacheValidDays = 7

function Get-CachedLicense {
    [CmdletBinding()]
    param(
        [string]$LicenseKey
    )

    try {
        if (Test-Path $script:LicenseCachePath) {
            $cache = Get-Content $script:LicenseCachePath -Raw | ConvertFrom-Json

            if ($cache.licenseKey -eq $LicenseKey) {
                $cachedDate = [DateTime]::Parse($cache.cachedAt)
                $daysSinceCached = (Get-Date) - $cachedDate

                if ($daysSinceCached.TotalDays -lt $script:LicenseCacheValidDays) {
                    Write-Verbose "Using cached license (cached $([int]$daysSinceCached.TotalDays) days ago)"
                    return @{
                        isValid = $true
                        plan = $cache.plan
                        email = $cache.email
                        cached = $true
                        cachedAt = $cache.cachedAt
                    }
                }
            }
        }
    } catch {
        Write-Verbose "Could not read license cache: $($_.Exception.Message)"
    }

    return $null
}

function Save-LicenseCache {
    [CmdletBinding()]
    param(
        [string]$LicenseKey,
        [string]$Email,
        [string]$Plan
    )

    try {
        $cacheDir = Split-Path $script:LicenseCachePath
        if (-not (Test-Path $cacheDir)) {
            New-Item -ItemType Directory -Path $cacheDir -Force | Out-Null
        }

        $cache = @{
            licenseKey = $LicenseKey
            email = $Email
            plan = $Plan
            cachedAt = (Get-Date).ToString("o")
            computerName = $env:COMPUTERNAME
        } | ConvertTo-Json

        $cache | Out-File -FilePath $script:LicenseCachePath -Encoding UTF8 -Force
        Write-Verbose "License cached for offline use"
    } catch {
        Write-Verbose "Could not save license cache: $($_.Exception.Message)"
    }
}

function Test-RescuePCLicense {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$CustomerEmail,

        [Parameter(Mandatory)]
        [string]$LicenseKey,

        [switch]$Silent
    )

    $bodyObject = @{
        email      = $CustomerEmail
        licenseKey = $LicenseKey
    }

    $bodyJson = $bodyObject | ConvertTo-Json -Compress

    try {
        $uri = "https://www.rescuepcrepairs.com/api/license-verify/"

        $devOverride = $env:RESCUEPC_DEV_API
        if ($devOverride) {
            $uri = "$devOverride/api/license-verify/"
            Write-Verbose "Using dev API: $uri"
        }

        $headers = @{
            "User-Agent" = "RescuePC-Toolkit/2.0 (Windows NT; Desktop Application)"
            "Accept" = "application/json"
            "X-Client-Type" = "desktop-app"
        }

        $response = Invoke-RestMethod -Method Post -Uri $uri -Body $bodyJson -ContentType 'application/json' -Headers $headers -TimeoutSec 15

        if ($response.isValid) {
            Save-LicenseCache -LicenseKey $LicenseKey -Email $CustomerEmail -Plan $response.plan
        }

        return $response
    }
    catch {
        Write-Verbose "Network error, checking cached license..."
        $cached = Get-CachedLicense -LicenseKey $LicenseKey

        if ($cached) {
            Write-Verbose "Using cached license for offline mode"
            return $cached
        }

        if (-not $Silent) {
            throw
        }

        return @{
            isValid = $false
            error   = $_.Exception.Message
        }
    }
}

function Invoke-RescuePCLicenseCheck {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string]$Email,

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

        [Parameter(Mandatory = $false)]
        [string]$ApiBaseUrl = "http://localhost:3000"
    )

    $ErrorActionPreference = "Stop"

    $body = @{
        email      = $Email
        licenseKey = $LicenseKey
    } | ConvertTo-Json

    $url = "$ApiBaseUrl/api/activate"

    Write-Verbose "Calling $url for license check..."
    Write-Verbose "Email: $Email"

    $response = Invoke-RestMethod -Uri $url -Method Post -Body $body -ContentType "application/json"

    if (-not $response.valid) {
        throw "License invalid or expired: $($response.error)"
    }

    $licenseStatePath = "$env:ProgramData\RescuePC\license_state.json"
    $state = @{
        email      = $response.email
        role       = $response.role
        token      = $response.token
        activated  = (Get-Date).ToString("o")
    } | ConvertTo-Json -Depth 5

    $dir = Split-Path $licenseStatePath
    if (-not (Test-Path $dir)) {
        New-Item -ItemType Directory -Path $dir -Force | Out-Null
    }

    $state | Out-File -FilePath $licenseStatePath -Encoding UTF8

    Write-Host "License is VALID. Role: $($response.role). Email: $($response.email)" -ForegroundColor Green
    return $response
}

Export-ModuleMember -Function Test-RescuePCLicense, Invoke-RescuePCLicenseCheck