param(
    [Parameter(Mandatory=$true)]
    [string]$TableName
)

function Install-RequiredModules {
    $requiredModule = "SqlServer"
    
    if (-not (Get-Module -ListAvailable -Name $requiredModule)) {
        Write-Host "Installazione modulo $requiredModule..."
        try {
            Install-Module -Name $requiredModule -Force -AllowClobber -Scope CurrentUser
        }
        catch {
            Write-Error "Errore durante l'installazione del modulo $requiredModule. Eseguire PowerShell come amministratore e riprovare."
            exit 1
        }
    }
}

# Verifica e installa moduli necessari
Install-RequiredModules

# Importa configurazione
. "$PSScriptRoot\conf.ps1"

$InputFile = Join-Path $PSScriptRoot "..\extract\$TableName.csv"

if (-not (Test-Path $InputFile)) {
    Write-Error "File non trovato: $InputFile"
    exit 1
}

try {
    # Import SQL Server module if not already loaded
    if (-not (Get-Module -Name SqlServer)) {
        Import-Module SqlServer
    }

    Write-Host "Lettura dati da: $InputFile"
    $data = Import-Csv -Path $InputFile -Delimiter ";"
    
    if ($data.Count -eq 0) {
        Write-Error "Il file CSV è vuoto"
        exit 1
    }

    Write-Host "Connessione a $env:dbHostOutput, database $env:dbName..."
    
    # Get column names from CSV
    $columns = $data[0].PSObject.Properties.Name
    $columnList = ($columns | ForEach-Object { "[$_]" }) -join ","
    
    # Function to format value for SQL
    function Format-SqlValue {
        param($value)
        if ([string]::IsNullOrEmpty($value)) {
            return "NULL"
        }
        # Try to parse as date
        [datetime]$dateValue = [datetime]::MinValue
        if ([datetime]::TryParse($value, [ref]$dateValue)) {
            return "'" + $dateValue.ToString("yyyy-MM-dd HH:mm:ss") + "'"
        }
        return "'" + $value.Replace("'", "''") + "'"
    }

    # Process each row
    foreach ($row in $data) {
        # Create value list for this row
        $values = @()
        foreach ($column in $columns) {
            $value = $row.$column
            $values += Format-SqlValue $value
        }
        
        # Create and execute insert query for this row
        $valuesList = $values -join ","
        $query = "INSERT INTO $TableName ($columnList) VALUES ($valuesList)"
        
        # Execute insert for each row
        $connectionString = "Server=$env:dbHostOutput;Database=$env:dbName;User Id=$env:dbUser;Password=$env:dbPassword;Encrypt=False"
        
        Invoke-Sqlcmd -ConnectionString $connectionString `
                      -Query $query
    }
    
    Write-Host "Dati importati con successo nella tabella: $TableName"
}
catch {
    Write-Error "Errore durante l'importazione dei dati: $_"
    exit 1
}
