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

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

# Carica l'assembly System.Data
Add-Type -AssemblyName System.Data

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

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

try {


    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:dbNameOutput..."
    
    # 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:dbNameOutput;User Id=$env:dbUserOutput;Password=$env:dbPasswordOutput;TrustServerCertificate=True"
        
        $connection = New-Object System.Data.SqlClient.SqlConnection($connectionString)
        $command = New-Object System.Data.SqlClient.SqlCommand($query, $connection)
        
        try {
            $connection.Open()
            $command.ExecuteNonQuery() | Out-Null
        }
        finally {
            if ($connection.State -eq 'Open') {
                $connection.Close()
            }
        }
    }
    
    Write-Host "Dati importati con successo nella tabella: $TableName"
}
catch {
    Write-Error "Errore durante l'importazione dei dati: $_"
    exit 1
}
