#Requires -Version 5.1
<#
.SYNOPSIS
  Reset an ERP user's password on the Hetzner server (passwords cannot be read back — only reset).

.EXAMPLE
  cd deploy\hetzner
  .\Reset-TenantUserPassword.ps1 -Username cassidy -NewPassword "YourNewPass123!"
#>
param(
    [Parameter(Mandatory = $true)]
    [string]$Username,
    [Parameter(Mandatory = $true)]
    [string]$NewPassword
)

$ErrorActionPreference = "Stop"
. (Join-Path $PSScriptRoot "production.local.ps1")

if ($NewPassword.Length -lt 6) {
    Write-Host "Password must be at least 6 characters." -ForegroundColor Red
    exit 1
}

$deployKey = (& "$PSScriptRoot\_prepare-deploy-key.ps1" | Select-Object -Last 1).Trim()
$sshArgs = @("-i", $deployKey, "-o", "IdentitiesOnly=yes", "-o", "BatchMode=yes")

$pyUser = $Username.Replace("'", "''")
$pyPass = $NewPassword.Replace("'", "''")

$remote = @"
cd /opt/cnperp && source .venv/bin/activate && export PYTHONPATH=/opt/cnperp && python - <<'PY'
from datetime import datetime
from app.core.database import SessionLocal
from app.core.security import get_password_hash
from app.models.user import User

db = SessionLocal()
u = db.query(User).filter(User.username == '$pyUser').first()
if not u:
    print('ERROR: user not found: $pyUser')
    exit(1)
u.password_digest = get_password_hash('$pyPass')
u.password_changed_at = datetime.utcnow()
u.active = True
db.commit()
print('OK: password reset for', u.username, 'company_id=', u.company_id)
db.close()
PY
"@ -replace "`r", ""

Write-Host "Resetting password for '$Username' on ${ServerIp}..." -ForegroundColor Cyan
ssh @sshArgs "root@$ServerIp" $remote
if ($LASTEXITCODE -ne 0) { exit 1 }
Write-Host "Done. Login at https://erp.cnpsolutions.co.bw/static/login.html" -ForegroundColor Green
Write-Host "  Company code: COMPUTIN  |  Branch: COMPUTIN-HQ  |  Username: $Username" -ForegroundColor Green
Remove-Item -Force $deployKey, "$deployKey.pub" -ErrorAction SilentlyContinue
