$server   = "CPMIN-DL343"
$database = "Test_database"
$folder   = "C:\Users\gunjanr\Downloads\Telegram Desktop\DB"
$logFile  = "C:\Users\gunjanr\Documents\deployment_log.txt"

Import-Module SqlServer -ErrorAction Stop

# Reset log file
if (Test-Path $logFile) { Remove-Item $logFile }

# Create DB if not exists
Invoke-Sqlcmd -ServerInstance $server -Database "master" `
-Query "IF DB_ID('$database') IS NULL CREATE DATABASE [$database]" `
-TrustServerCertificate

Write-Host "Database Ready: $database" -ForegroundColor Green

# Get SQL files
$files = Get-ChildItem -Path $folder -Recurse -Filter *.sql

# Sort files (execution order)
$sortedFiles = $files | Sort-Object {
    $path = $_.FullName.ToLower()

    if ($path -like "*\tables\*") {1}
    elseif ($path -like "*\constraints\*primary*") {2}
    elseif ($path -like "*\indexes\*") {3}
    elseif ($path -like "*\constraints\*fk*") {4}
    elseif ($path -like "*\constraints\*") {5}
    elseif ($path -like "*\functions\*") {6}
    elseif ($path -like "*\procedures\*") {7}
    elseif ($path -like "*\views\*") {8}
    elseif ($path -like "*\triggers\*") {9}
    else {10}
}, Name

Write-Host "Total files found: $($sortedFiles.Count)" -ForegroundColor Yellow

# Counters
$successCount = 0
$skipCount    = 0
$errorCount   = 0

# Execute files
foreach ($file in $sortedFiles) {

    Write-Host "Running: $($file.FullName)" -ForegroundColor Cyan

    try {
        $content = Get-Content $file.FullName -Raw

        # Extract SET statements
        $setStatements = @()
        if ($content -match "(?i)SET\s+ANSI_NULLS\s+ON") {
            $setStatements += "SET ANSI_NULLS ON"
        }
        if ($content -match "(?i)SET\s+QUOTED_IDENTIFIER\s+ON") {
            $setStatements += "SET QUOTED_IDENTIFIER ON"
        }

        # Remove SET lines
        $cleanContent = $content -replace "(?im)^\s*SET\s+ANSI_NULLS\s+ON\s*$", ""
        $cleanContent = $cleanContent -replace "(?im)^\s*SET\s+QUOTED_IDENTIFIER\s+ON\s*$", ""

        # Run SET statements first
        foreach ($stmt in $setStatements) {
            Invoke-Sqlcmd `
                -ServerInstance $server `
                -Database $database `
                -Query $stmt `
                -TrustServerCertificate `
                -ErrorAction Stop
        }

        # Split by GO
        $batches = $cleanContent -split "(?im)^\s*GO\s*$"

        foreach ($batch in $batches) {

            $sql = $batch.Trim()
            if ([string]::IsNullOrWhiteSpace($sql)) { continue }

            try {
                Invoke-Sqlcmd `
                    -ServerInstance $server `
                    -Database $database `
                    -Query $sql `
                    -TrustServerCertificate `
                    -QueryTimeout 0 `
                    -ErrorAction Stop
            }
            catch {
                $errorMessage = $_.Exception.Message

                # Skip "already exists"
                if ($errorMessage -match "already exists|duplicate|exists") {
                    Write-Host "Skipped (Already Exists): $($file.Name)" -ForegroundColor Yellow
                    $skipCount++
                    continue
                }

                # Log real error
                Write-Host "Error in batch: $($file.Name)" -ForegroundColor Red
                Write-Host $errorMessage -ForegroundColor DarkRed

                Add-Content $logFile "File: $($file.FullName)"
                Add-Content $logFile "Error: $errorMessage"
                Add-Content $logFile "-----------------------------"

                $errorCount++
                continue
            }
        }

        Write-Host "Completed: $($file.Name)" -ForegroundColor Green
        $successCount++
    }
    catch {
        $errorMessage = $_.Exception.Message

        Write-Host "Error in file: $($file.FullName)" -ForegroundColor Red
        Write-Host $errorMessage -ForegroundColor DarkRed

        Add-Content $logFile "File: $($file.FullName)"
        Add-Content $logFile "Error: $errorMessage"
        Add-Content $logFile "-----------------------------"

        $errorCount++
        continue
    }
}

# Final Summary
Write-Host "`n===== DEPLOYMENT SUMMARY =====" -ForegroundColor Cyan
Write-Host "Successful Files : $successCount" -ForegroundColor Green
Write-Host "Skipped Files    : $skipCount" -ForegroundColor Yellow
Write-Host "Failed Files     : $errorCount" -ForegroundColor Red

Write-Host "`nDeployment completed." -ForegroundColor Green