<#
.SYNOPSIS
    VelaPanel admin account recovery — retrieve panel usernames and reset username / email / password.

.DESCRIPTION
    Works directly against C:\velapanel.com\data\panel.db. Passwords are stored one-way
    hashed (ASP.NET Core Identity) and CANNOT be read back — this tool can only RESET them.
    A reset also unlocks the account, clears failed-login counters, reactivates it, and
    rotates the security stamp so any existing login sessions are invalidated.

.EXAMPLE
    # See all admin accounts (recover a forgotten username / email)
    .\reset-panel-admin.ps1 -List

.EXAMPLE
    # Reset just the password for a known account
    .\reset-panel-admin.ps1 -User admin@localhost -Password 'NewAdmin@Pass1!'

.EXAMPLE
    # Reset the username/email AND password in one go
    .\reset-panel-admin.ps1 -User admin@localhost -NewUserName newadmin@site.com -Email newadmin@site.com -Password 'NewAdmin@Pass1!'

.NOTES
    Password rules (enforced by the panel on next change): min 12 chars, upper + lower + digit + symbol.
#>
[CmdletBinding(DefaultParameterSetName = 'List')]
param(
    [Parameter(ParameterSetName = 'List')]
    [switch]$List,

    [Parameter(ParameterSetName = 'List')]
    [string]$Role = 'Admin',

    [Parameter(ParameterSetName = 'Set', Mandatory = $true)]
    [string]$User,                # existing Id, UserName or Email to locate the account

    [Parameter(ParameterSetName = 'Set')]
    [string]$NewUserName,         # optional new username

    [Parameter(ParameterSetName = 'Set')]
    [string]$Email,              # optional new email

    [Parameter(ParameterSetName = 'Set')]
    [string]$Password            # optional new password
)

$ErrorActionPreference = 'Stop'

$dotnet = 'C:\dotnet\dotnet.exe'
$binDir = Join-Path $PSScriptRoot 'AdminReset\bin'
$dll    = Join-Path $binDir 'AdminReset.dll'

if (-not (Test-Path $dotnet)) { throw "dotnet runtime not found at $dotnet" }
if (-not (Test-Path $dll))    { throw "Recovery tool not built. Missing: $dll" }

if ($PSCmdlet.ParameterSetName -eq 'List') {
    & $dotnet $dll list --role $Role
    return
}

$toolArgs = @('set', '--user', $User)
if ($NewUserName) { $toolArgs += @('--username', $NewUserName) }
if ($Email)       { $toolArgs += @('--email',    $Email) }
if ($Password)    { $toolArgs += @('--password', $Password) }

if (-not ($NewUserName -or $Email -or $Password)) {
    throw "Provide at least one of -NewUserName, -Email, -Password to reset."
}

& $dotnet $dll @toolArgs
