<?php

declare(strict_types=1);

namespace App\Business\Report;

use Symfony\Component\HttpFoundation\StreamedResponse;

final class CsvExportService
{
    /**
     * @param  list<string>  $headers
     * @param  iterable<array-key, list<string|null>>  $rows
     */
    public function download(string $filename, array $headers, iterable $rows): StreamedResponse
    {
        return response()->streamDownload(function () use ($headers, $rows): void {
            echo "\xEF\xBB\xBF";

            $handle = fopen('php://output', 'wb');

            if ($handle === false) {
                return;
            }

            fputcsv($handle, $headers);

            foreach ($rows as $row) {
                fputcsv($handle, $row);
            }

            fclose($handle);
        }, $filename, [
            'Content-Type' => 'text/csv; charset=UTF-8',
        ]);
    }
}