<?php

declare(strict_types=1);

namespace Ost\ReimportDataengine\Controller;

use Ost\ReimportDataengine\Service\ProductExportFeedBuilder;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\Routing\Attribute\Route;

#[Route(defaults: ['_routeScope' => ['storefront']])]
final class ExportController extends AbstractController
{
    public function __construct(
        private readonly ProductExportFeedBuilder $productExportFeedBuilder
    ) {
    }

    #[Route(
        path: '/reimport-dataengine/feed.csv',
        name: 'frontend.reimport-dataengine.feed',
        methods: ['GET']
    )]
    public function feed(SalesChannelContext $salesChannelContext): StreamedResponse
    {
        $response = new StreamedResponse(function () use ($salesChannelContext): void {
            $handle = fopen('php://output', 'wb');

            if ($handle === false) {
                throw new \RuntimeException('Unable to open the CSV output stream.');
            }

            $this->productExportFeedBuilder->streamToHandle($handle, $salesChannelContext);
            fclose($handle);
        });

        $response->headers->set('Content-Type', 'text/csv; charset=UTF-8');
        $response->headers->set('Content-Disposition', 'inline; filename="reimport-dataengine.csv"');

        return $response;
    }
}
