# Script per elencare gli oggetti del database
# Importa la configurazione
. $PSScriptRoot\conf.ps1

# Imposta il percorso di output nella cartella sql
$OutputPath = Join-Path $env:workdir "sql\stored"

# Importa il modulo SQL Server se non è già caricato
if (-not (Get-Module -Name SQLPS)) {
    Import-Module SQLPS -DisableNameChecking
}

try {
    # Query per ottenere l'elenco degli oggetti
    $query = @"
    SELECT 
        CASE type
            WHEN 'U' THEN 'Table'
            WHEN 'V' THEN 'View'
            WHEN 'P' THEN 'Stored Procedure'
            WHEN 'FN' THEN 'Function'
            WHEN 'TR' THEN 'Trigger'
            ELSE type
        END AS ObjectType,
        SCHEMA_NAME(schema_id) AS SchemaName,
        name AS ObjectName
    FROM sys.objects
    WHERE type IN ('U', 'V', 'P', 'FN', 'TR')
    ORDER BY ObjectType, SchemaName, ObjectName
"@

    # Esegui la query e salva i risultati
    $results = Invoke-Sqlcmd -ServerInstance $config.DbHostInput -Database $config.DbName -Username $config.DbUser -Password $config.DbPassword -Query $query

    # Prepara l'output
    $output = "Elenco oggetti del database $($config.DbName) su $($config.DbHostInput) il $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')`r`n"
    $output += "Tipo;Schema;Nome`r`n"

    # Formatta e aggiungi ogni oggetto all'output
    foreach ($row in $results) {
        $output += "$($row.ObjectType);$($row.SchemaName);$($row.ObjectName)`r`n"
    }

    # Scrivi il risultato su file
    $output | Out-File -FilePath (Join-Path -Path $OutputPath -ChildPath "_elenco_oggetti.csv") -Encoding UTF8

    Write-Host "Elenco oggetti salvato correttamente in _elenco_oggetti.csv"
}
catch {
    Write-Error "Si è verificato un errore: $_"
    exit 1
}