param(
    [Parameter(Mandatory = $true)]
    [string]$JobName,
    
    [Parameter(Mandatory = $true)]
    [ValidateSet('DEVL', 'TEST', 'PROD')]
    [string]$Env
)

try {
    Write-Host "Starting job $JobName in environment $Env at $(Get-Date)"

    # ------------------------------------------------------------
    # Extract JCL from JobName (ENV_FREQUENCY_JOB pattern)
    # ------------------------------------------------------------
    $JCL = $JobName -replace '^[A-Z]+_[A-Z]+_', ''
    Write-Host "Extracted JCL: $JCL from JobName: $JobName" -ForegroundColor Yellow

    # ------------------------------------------------------------
    # Environment-specific configuration
    # ------------------------------------------------------------
    switch ($Env.ToUpper()) {
        'DEVL' {
            $ComputerName = '10.57.110.120'
            $DatabaseName = 'DevlDUTASJobSchedule'
        }
        'TEST' {
            $ComputerName = '10.57.110.141'
            $DatabaseName = 'TestDUTASJobSchedule'
        }
        'PROD' {
            $ComputerName = '10.57.111.120'
            $DatabaseName = 'ProdDUTASJobSchedule'
        }
        default {
            throw "Invalid environment specified: $Env"
        }
    }

    # ------------------------------------------------------------
    # Remote credentials
    # (recommend moving credentials to secure vault for production)
    # ------------------------------------------------------------
    $username = "DUTASSQLAdminP@does.dcgov.priv"
    $password = "4ho@3Pr&Xof8" | ConvertTo-SecureString -AsPlainText -Force
    $credential = New-Object System.Management.Automation.PSCredential($username, $password)

    # ------------------------------------------------------------
    # Execute job remotely using the extracted JCL
    # ------------------------------------------------------------
    Write-Host "Connecting to remote server $ComputerName ..."
    $exitCode = Invoke-Command -ComputerName $ComputerName `
        -Credential $credential `
        -Authentication CredSSP `
        -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck) `
        -ArgumentList $JobName, $JCL, $Env `
        -ScriptBlock {
            param($JobName, $JCL, $Env)

            Write-Host "Remote execution - JobName: $JobName, JCL: $JCL, Env: $Env"
            
            $process = Start-Process -FilePath "powershell.exe" `
                                     -ArgumentList "-ExecutionPolicy Bypass -File `"E:\PSScript\RCSubmit-Job.ps1`" -JobName `"$JCL`" -Env `"$Env`"" `
                                     -NoNewWindow -Wait -PassThru
            return $process.ExitCode
        }

    if ($exitCode -eq 0) {
        Write-Host "Job $JobName (JCL: $JCL) completed successfully at $(Get-Date)" -ForegroundColor Green
    } else {
        Write-Error "Job $JobName (JCL: $JCL) failed with exit code: $exitCode"
    }
}
catch {
    Write-Error "Job $JobName failed with error: $($_.Exception.Message)"
    $exitCode = 1
}
finally {
    # ------------------------------------------------------------
    # Log exit code to the appropriate database
    # ------------------------------------------------------------
    try {
        $connectionString = "Server=localhost;Database=$DatabaseName;Trusted_Connection=true;"
        $connection = New-Object System.Data.SqlClient.SqlConnection($connectionString)
        $connection.Open()
        
        $command = $connection.CreateCommand()
        $command.CommandText = @"
            INSERT INTO dbo.JobExitCodes (JobName, RunDate, ExitCode, RecordedTime)
            VALUES ('$JobName', CAST(GETDATE() AS DATE), $exitCode, GETDATE());
"@
        $command.ExecuteNonQuery()
        $connection.Close()
        Write-Host "Exit code $exitCode logged to database $DatabaseName for job $JobName"
    }
    catch {
        $errorMsg = $_.Exception.Message
        Write-Host "Failed to log exit code to database $DatabaseName`: $errorMsg"
    }
}

exit $exitCode