<#
.SYNOPSIS
    Validates DBAOps license - returns valid, expired, or trial
.DESCRIPTION
    Checks license.LicenseKeys in FuturisticREPO or config for license validity.
    Also supports LicenseKey in DBAOps.config.json for trial/standalone.
.EXAMPLE
    .\Test-DBAOpsLicense.ps1
    Returns: valid | expired | trial
#>
param(
    [string]$SqlServer = $null,
    [string]$Database = $null,
    [string]$ConfigPath = $null
)

$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$defaultConfigPath = Join-Path (Split-Path -Parent $scriptDir) "Config\DBAOps.config.json"

if (-not $ConfigPath) { $ConfigPath = $defaultConfigPath }

# Load config
$cfg = $null
if (Test-Path $ConfigPath) {
    try {
        $cfg = Get-Content $ConfigPath -Raw | ConvertFrom-Json
    } catch { }
}

$sqlInstance = if ($SqlServer) { $SqlServer } elseif ($cfg -and $cfg.CentralServer) { $cfg.CentralServer } else { $env:COMPUTERNAME }
$db = if ($Database) { $Database } elseif ($cfg -and $cfg.Database) { $cfg.Database } else { "DBAOpsRepository" }
$licenseKey = if ($cfg -and $cfg.LicenseKey) { $cfg.LicenseKey } else { $null }

# Check config LicenseKey (trial/standalone)
if ($licenseKey) {
    $lk = $licenseKey.ToString().ToUpper()
    if ($lk -eq "TRIAL" -or $lk -like "*TRIAL*") {
        Write-Output "trial"
        exit 0
    }
    # Could add more validation (format, expiry from config) - for now assume valid if not TRIAL
    Write-Output "valid"
    exit 0
}

# Check database license.LicenseKeys (FuturisticREPO has this schema)
$dbToCheck = if ($db -eq "FuturisticREPO") { "FuturisticREPO" } else { "DBAOpsRepository" }

try {
    $checkSchema = "SELECT 1 FROM sys.schemas s JOIN sys.tables t ON t.schema_id = s.schema_id WHERE s.name = 'license' AND t.name = 'LicenseKeys'"
    $conn = New-Object System.Data.SqlClient.SqlConnection
    $conn.ConnectionString = "Server=$sqlInstance;Database=$dbToCheck;Integrated Security=True;TrustServerCertificate=True"
    $conn.Open()
    $cmd = $conn.CreateCommand()
    $cmd.CommandText = $checkSchema
    $cmd.CommandTimeout = 5
    $hasSchema = $null -ne $cmd.ExecuteScalar()
    if ($hasSchema) {
        $query = "SELECT TOP 1 CASE WHEN ExpiresAt >= GETDATE() AND IsActive = 1 THEN 'valid' ELSE 'expired' END AS Status FROM license.LicenseKeys WHERE IsActive = 1 ORDER BY ExpiresAt DESC"
        $cmd.CommandText = $query
        $reader = $cmd.ExecuteReader()
        if ($reader.Read()) {
            $status = $reader["Status"]
            $reader.Close()
            $conn.Close()
            Write-Output $status
            exit 0
        }
        $reader.Close()
    }
    $conn.Close()
} catch {
    # No license schema or connection failed - assume trial
}

Write-Output "trial"
exit 0
