$ErrorActionPreference = "Stop"

$workbookPath = (Get-ChildItem -LiteralPath "." -Filter "*.xlsx" | Where-Object { $_.Name -notlike "*.backup-*" -and $_.Name -notlike "e2e-cases*.backup-*" } | Select-Object -First 1).FullName
if ([string]::IsNullOrWhiteSpace($workbookPath)) {
    throw "No xlsx workbook found in current directory."
}
$payloadPath = (Resolve-Path ".\scripts\acceptance_income_flow_cases.json").Path
$payload = Get-Content -LiteralPath $payloadPath -Raw -Encoding UTF8 | ConvertFrom-Json

$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$excel.DisplayAlerts = $false
$wb = $null

function Set-RowValues {
    param([object]$Worksheet, [int]$Row, [object[]]$Values)
    for ($i = 0; $i -lt $Values.Count; $i++) {
        $Worksheet.Cells.Item($Row, $i + 1).Value2 = [string]$Values[$i]
    }
    $Worksheet.Rows.Item($Row).WrapText = $true
    $Worksheet.Rows.Item($Row).VerticalAlignment = -4160
}

function Append-Rows {
    param([object]$Workbook, [string]$SheetName, [object[]]$Rows)
    $ws = $Workbook.Worksheets.Item($SheetName)
    foreach ($values in $Rows) {
        $row = $ws.UsedRange.Rows.Count + 1
        [void]$ws.Rows.Item($row - 1).Copy()
        [void]$ws.Rows.Item($row).PasteSpecial(-4122)
        Set-RowValues -Worksheet $ws -Row $row -Values $values
    }
}

function Append-To-Case {
    param(
        [object]$Workbook,
        [string]$SheetName,
        [string]$CaseId,
        [string]$ExpectedAppend,
        [string]$CrossAppend
    )
    $ws = $Workbook.Worksheets.Item($SheetName)
    $found = $ws.Columns.Item(1).Find($CaseId)
    if ($found -eq $null) { return }
    $row = $found.Row
    $expectedCol = 9
    $crossCol = 10
    $currentExpected = [string]$ws.Cells.Item($row, $expectedCol).Value2
    if ($currentExpected -notlike "*$ExpectedAppend*") {
        $ws.Cells.Item($row, $expectedCol).Value2 = ($currentExpected.TrimEnd() + "`nAdd: " + $ExpectedAppend)
    }
    $currentCross = [string]$ws.Cells.Item($row, $crossCol).Value2
    if ($currentCross -notlike "*$CrossAppend*") {
        $ws.Cells.Item($row, $crossCol).Value2 = ($currentCross.TrimEnd() + "`nAdd: " + $CrossAppend)
    }
    $ws.Rows.Item($row).WrapText = $true
}

try {
    $wb = $excel.Workbooks.Open($workbookPath)

    foreach ($update in $payload.updates) {
        foreach ($sheetName in $update.sheets) {
            Append-To-Case -Workbook $wb -SheetName ([string]$sheetName) -CaseId ([string]$update.caseId) -ExpectedAppend ([string]$update.expectedAppend) -CrossAppend ([string]$update.crossAppend)
        }
    }

    foreach ($sheetName in $payload.caseSheets) {
        Append-Rows -Workbook $wb -SheetName ([string]$sheetName) -Rows $payload.caseRows
    }

    foreach ($sheet in $payload.extraSheets.PSObject.Properties) {
        Append-Rows -Workbook $wb -SheetName ([string]$sheet.Name) -Rows $sheet.Value
    }

    $wb.Save()
    $wb.Close($true)
    Write-Output "UPDATED|$workbookPath"
}
finally {
    if ($wb -ne $null) {
        [System.Runtime.InteropServices.Marshal]::ReleaseComObject($wb) | Out-Null
    }
    $excel.Quit()
    [System.Runtime.InteropServices.Marshal]::ReleaseComObject($excel) | Out-Null
}
