# Setup SQL Server DB cho SOLUTION_ERP trên VPS chia sẻ với VIETREPORT.
# Tạo database + grant quyền cho user vrapp (đã có sẵn trên server).
# Dùng Invoke-Sqlcmd (PowerShell SqlServer module) — không cần sqlcmd.exe binary.
# Idempotent: chạy lại không phá gì.
#
# Usage (chạy trên VPS với admin privilege):
#   Install-Module SqlServer -Force -Scope AllUsers  # 1 lần duy nhất nếu chưa có
#   .\setup-sql-db.ps1 -SaPassword 'your-sa-password'
#
# Prereq:
#   - SQL Server cài sẵn (mặc định instance SQLEXPRESS)
#   - Login vrapp đã tồn tại (dùng chung với VIETREPORT)
#   - Module SqlServer installed

param(
    [Parameter(Mandatory=$true)] [string]$SaPassword,
    [string]$Server = ".\SQLEXPRESS",
    [string]$Database = "SolutionErp",
    [string]$AppUser = "vrapp"
)

$ErrorActionPreference = 'Stop'
Import-Module SqlServer -ErrorAction Stop

$secureSa = ConvertTo-SecureString $SaPassword -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential('sa', $secureSa)

function Invoke-Sql($query, [switch]$NoDb) {
    $params = @{
        ServerInstance = $Server
        Credential     = $creds
        Query          = $query
        TrustServerCertificate = $true
        ErrorAction    = 'Stop'
    }
    if (-not $NoDb) { $params.Database = 'master' }
    Invoke-Sqlcmd @params
}

Write-Host "==> Check SQL Server reachable ($Server)"
$ver = Invoke-Sql "SELECT @@VERSION AS V" -NoDb
Write-Host "  $($ver.V -split '`n' | Select-Object -First 1)"

Write-Host "`n==> Check login '$AppUser' exists"
$check = Invoke-Sql "SELECT name FROM sys.sql_logins WHERE name = '$AppUser'"
if (-not $check -or $check.name -ne $AppUser) {
    Write-Warning "Login '$AppUser' KHONG ton tai. Tao truoc voi:"
    Write-Warning "  Invoke-Sqlcmd -ServerInstance '$Server' -Credential <sa-cred> -Query `"CREATE LOGIN [$AppUser] WITH PASSWORD='...', CHECK_POLICY=OFF;`""
    throw "Login vrapp missing"
}
Write-Host "  OK ($AppUser exists)"

Write-Host "`n==> Create database '$Database' (if not exists)"
Invoke-Sql @"
IF DB_ID(N'$Database') IS NULL
BEGIN
    CREATE DATABASE [$Database];
    PRINT 'Created database $Database';
END
ELSE PRINT 'Database $Database already exists';
"@

Write-Host "`n==> Grant db_owner cho '$AppUser' tren '$Database'"
$grantQuery = @"
USE [$Database];
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '$AppUser')
BEGIN
    CREATE USER [$AppUser] FOR LOGIN [$AppUser];
    PRINT 'Created user $AppUser in DB';
END
ELSE PRINT 'User $AppUser already exists in DB';
ALTER ROLE db_owner ADD MEMBER [$AppUser];
PRINT 'Added $AppUser to db_owner';
"@

Invoke-Sqlcmd -ServerInstance $Server -Credential $creds -Database $Database -Query $grantQuery -TrustServerCertificate

Write-Host "`n✅ SQL Server setup DONE" -ForegroundColor Green
Write-Host "   Server:   $Server"
Write-Host "   Database: $Database"
Write-Host "   App user: $AppUser (db_owner)"
Write-Host "   Connection string production:"
Write-Host "     Server=$Server;Database=$Database;User Id=$AppUser;Password=***;MultipleActiveResultSets=true;TrustServerCertificate=true;Encrypt=true"
