# $DebugPreference = "Continue" #SilentlyContinue vs Continue 

function authenticate($defaultUser) {
    Write-Host "Please authenticate using the credentials popup to continue"
    $authenticationResult = $null; #Clear out any previous runs
    $authenticationResult = $host.UI.PromptForCredential("Server Authentication: anvil.nz", "Please enter your username and password for anvil.nz:", "$defaultUser", "")
    if ($null -ne $authenticationResult) {
        return $authenticationResult
    } 
    Write-Host "Authentication Failed/Cancelled"
    break
}

# URL of the file to download
$url = "https://new.anvil.nz/dir/CustomerInfo.csv"

Write-Debug "Current PS Root: $PSScriptRoot"

# Define the directory and output file path
$directory = "$PSScriptRoot\..\CustomerConfigs"
$output_file = "$directory\CustomerInfo.csv"

# Check if the directory exists; if not, create it
if (-not (Test-Path -Path $directory)) {
    New-Item -ItemType Directory -Path $directory -Force
    Write-Debug "Directory created: $directory"
} else {
    Write-Debug "Directory already exists: $directory"
}

# Use Invoke-WebRequest to download the file with basic auth
$cred = authenticate "spark"
Invoke-WebRequest -Uri $url -OutFile $output_file -Credential $cred

# Check if the file was downloaded successfully
if (Test-Path $output_file) {
    Write-Host "Download successful: $output_file"
} else {
    Write-Host "Download failed. Please check your credentials and try again."
}