# Deploy FIXED Database API to AD2
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)

Write-Host "========================================" -ForegroundColor Red
Write-Host "EMERGENCY FIX - Database API" -ForegroundColor Red
Write-Host "========================================`n" -ForegroundColor Red

# Step 1: Mount AD2 share
Write-Host "[1/3] Mounting AD2 C$ share..." -ForegroundColor Green
New-PSDrive -Name AD2 -PSProvider FileSystem -Root "\\192.168.0.6\C$" -Credential $cred -ErrorAction Stop | Out-Null
Write-Host "  [OK] Share mounted" -ForegroundColor Green

# Step 2: Deploy fixed api.js (already have backup from before)
Write-Host "`n[2/3] Deploying FIXED api.js..." -ForegroundColor Green
$fixedContent = Get-Content "D:\ClaudeTools\api-js-fixed.js" -Raw
$fixedContent | Set-Content "AD2:\Shares\testdatadb\routes\api.js" -Encoding UTF8
Write-Host "  [OK] Fixed api.js deployed" -ForegroundColor Green
Write-Host "  [FIXED] Removed WAL mode pragma (conflicts with readonly)" -ForegroundColor Yellow
Write-Host "  [FIXED] Removed synchronous pragma (requires write access)" -ForegroundColor Yellow
Write-Host "  [KEPT] Cache size: 64MB" -ForegroundColor Green
Write-Host "  [KEPT] Memory-mapped I/O: 256MB" -ForegroundColor Green
Write-Host "  [KEPT] Timeout: 10 seconds" -ForegroundColor Green

# Step 3: Verify deployment
Write-Host "`n[3/3] Verifying deployment..." -ForegroundColor Green
$deployedFile = Get-Item "AD2:\Shares\testdatadb\routes\api.js"
Write-Host "  [OK] File size: $($deployedFile.Length) bytes" -ForegroundColor Green
Write-Host "  [OK] Modified: $($deployedFile.LastWriteTime)" -ForegroundColor Green

# Cleanup
Remove-PSDrive -Name AD2 -ErrorAction SilentlyContinue

Write-Host "`n========================================" -ForegroundColor Green
Write-Host "Fix Deployed Successfully" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
Write-Host "`n[ACTION REQUIRED] Restart Node.js Server:" -ForegroundColor Yellow
Write-Host "  1. Stop: taskkill /F /IM node.exe" -ForegroundColor Cyan
Write-Host "  2. Start: cd C:\Shares\testdatadb && node server.js" -ForegroundColor Cyan
Write-Host "`nThe database should now work correctly!" -ForegroundColor Green
Write-Host "========================================`n" -ForegroundColor Green
