<?php

declare(strict_types=1);

namespace KupShop\FeedsBundle\Formatter;

use KupShop\FeedsBundle\Dto\FeedItem;
use KupShop\KupShopBundle\Util\Excel\ExcelGenerator;

class StreamedXLSXFormatter extends StreamedCSVFormatter
{
    public function __construct(
        private ExcelGenerator $excelGenerator,
    ) {
    }

    public static function getType(): string
    {
        return 'xlsx';
    }

    public static function getContentType(): string
    {
        return 'application/vnd.ms-excel';
    }

    /**
     * @param \Generator<int, FeedItem> $data
     */
    public function process(array $configuration, \Generator $data): void
    {
        $data = $this->getFlattenedGenerator($configuration, $data);

        $header = [];
        // create header by first item
        if ($first = $data->current()) {
            foreach (array_keys($first) as $key) {
                $header[$key] = ['name' => $key];
            }
        }

        $data->rewind();

        // use generateExcelInternal bcs headers (filename, content type) are set implicitly by feeds route
        $this->excelGenerator->generateExcelInternal($header, $data);
    }
}
