<?php

namespace idoit\Module\SyneticsFlows\Export;

use idoit\Module\SyneticsFlows\Automation\Automation;
use idoit\Module\SyneticsFlows\Export\Formatter\ExportFormatterInterface;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

class FlowsExportService
{
    private const HIDDEN_DATA_KEYS = [
        'createdBy',
        'execution',
        'status',
    ];

    /**
     * @param iterable $formatters
     */
    public function __construct(private iterable $formatters)
    {
    }

    /**
     * @param string $format
     *
     * @param array $automations
     *
     * @return string
     */
    public function export(string $format, array $automations): string
    {
        foreach ($this->formatters as $formatter) {
            if (!$formatter instanceof ExportFormatterInterface || !$formatter->support($format)) {
                continue;
            }

            return $formatter->format($this->prepareData($automations));
        }

        throw new BadRequestHttpException("Export format is not supported");
    }

    /**
     * @param array $automations
     *
     * @return array|Automation[]
     */
    private function prepareData(array $automations): array
    {
        return array_map(
            function (Automation $flow) {
                $data = $flow->jsonSerialize();
                foreach (self::HIDDEN_DATA_KEYS as $key) {
                    unset($data[$key]);
                }
                return $data;
            },
            $automations
        );
    }
}