<?php

declare(strict_types=1);

namespace Plugin\tnt_international_phone\src\Admin;

/**
 * Serializes invalid-phone log rows to CSV (extracted from the report so the
 * export format is unit-testable without HTTP headers / exit).
 */
final class InvalidPhoneCsv
{
    public const array COLUMNS = ['id', 'form', 'field', 'raw_value', 'country_hint', 'reason', 'created_at'];

    public const array MODIFIED_COLUMNS = [
        'id', 'form', 'field', 'before_value', 'after_value', 'country_hint', 'created_at',
    ];

    /** @param list<string> $columns */
    public function __construct(private readonly array $columns = self::COLUMNS)
    {
    }

    /**
     * @param resource               $handle open writable stream
     * @param iterable<object> $rows
     */
    public function write($handle, iterable $rows): void
    {
        \fputcsv($handle, $this->columns, ',', '"', '\\');
        foreach ($rows as $row) {
            $line = [];
            foreach ($this->columns as $column) {
                $line[] = $row->{$column} ?? null;
            }
            \fputcsv($handle, $line, ',', '"', '\\');
        }
    }
}
