<?php
declare(strict_types=1);

namespace Autogedal\EanTools\Model\Tool;

use Autogedal\EanTools\Model\ResultStorage;
use Throwable;

class ExportScheduler
{
    public function __construct(private readonly ResultStorage $storage)
    {
    }

    public function scheduleUsed(string $format): string
    {
        return $this->schedule('used', $format);
    }

    public function scheduleInvalid(string $format): string
    {
        return $this->schedule('invalid', $format);
    }

    public function scheduleDuplicates(string $format): string
    {
        return $this->schedule('duplicates', $format);
    }

    public function scheduleMissing(array $filters, string $format): string
    {
        return $this->schedule('missing', $format, ['filters' => $filters]);
    }

    public function scheduleValidation(array $uploaded, string $format): string
    {
        $runId = $this->storage->createRun('validator');

        try {
            $inputFile = $this->storage->storeInputFile(
                $runId,
                (string)$uploaded['path'],
                (string)$uploaded['name']
            );
            $this->storage->queue($runId, $format, [
                'input_file' => $inputFile,
                'input_name' => (string)$uploaded['name'],
            ]);
        } catch (Throwable $exception) {
            $this->storage->fail($runId, (string)__('The file could not be prepared for processing.'));
            throw $exception;
        }

        return $runId;
    }

    private function schedule(string $tool, string $format, array $request = []): string
    {
        $runId = $this->storage->createRun($tool);

        try {
            $this->storage->queue($runId, $format, $request);
        } catch (Throwable $exception) {
            $this->storage->fail($runId, (string)__('The request could not be queued.'));
            throw $exception;
        }

        return $runId;
    }
}
