functions/private/Write-KlippyPrinterRegistry.ps1

function Write-KlippyPrinterRegistry {
    <#
    .SYNOPSIS
        Writes the printer registry to disk.

    .DESCRIPTION
        Writes the printer collection to the printers.json registry file.
        Validates uniqueness constraints before writing.

    .PARAMETER Printers
        The collection of printer objects to write.

    .OUTPUTS
        None
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [AllowEmptyCollection()]
        [System.Collections.Generic.List[PSCustomObject]]$Printers
    )

    $registryFile = Get-KlippyRegistryPath -FileOnly

    # Validate uniqueness constraints
    if ($Printers.Count -gt 0) {
        # Check for duplicate Ids
        $duplicateIds = $Printers | Group-Object -Property Id | Where-Object { $_.Count -gt 1 }
        if ($duplicateIds) {
            throw "Duplicate printer Id detected: $($duplicateIds.Name -join ', ')"
        }

        # Check for duplicate PrinterNames (case-insensitive)
        $duplicateNames = $Printers | Group-Object -Property { $_.PrinterName.ToLowerInvariant() } | Where-Object { $_.Count -gt 1 }
        if ($duplicateNames) {
            throw "Duplicate printer name detected: $($duplicateNames.Group[0].PrinterName)"
        }

        # Ensure only one default printer
        $defaultPrinters = $Printers | Where-Object { $_.IsDefault -eq $true }
        if ($defaultPrinters.Count -gt 1) {
            throw "Multiple default printers detected. Only one printer can be set as default."
        }
    }

    try {
        # Convert to clean objects for JSON serialization (remove PSTypeName)
        $cleanPrinters = $Printers | ForEach-Object {
            [PSCustomObject]@{
                Id          = $_.Id
                PrinterName = $_.PrinterName
                Uri         = $_.Uri
                ApiKey      = $_.ApiKey
                Description = $_.Description
                IsDefault   = $_.IsDefault
                CreatedAt   = $_.CreatedAt.ToString('o')
                ModifiedAt  = $_.ModifiedAt.ToString('o')
            }
        }

        $json = $cleanPrinters | ConvertTo-Json -Depth 10

        # Handle single item (ConvertTo-Json doesn't wrap single items in array)
        if ($Printers.Count -eq 1) {
            $json = "[$json]"
        }
        elseif ($Printers.Count -eq 0) {
            $json = "[]"
        }

        $json | Set-Content -Path $registryFile -Encoding UTF8 -Force -ErrorAction Stop
        Write-Verbose "Registry written to: $registryFile"
    }
    catch {
        throw "Failed to write registry file '$registryFile': $_"
    }
}