<?php

declare(strict_types=1);

namespace App\Domain\Shared\Application\CommandHandler;

use App\Domain\Shared\Application\Command\DeleteJobsByCriteria;
use App\Domain\Shared\Domain\Contract\CommandHandlerInterface;
use App\Domain\Shared\Domain\Contract\CommandInterface;
use App\Domain\Shared\Domain\Contract\JobRepositoryInterface;

readonly class DeleteJobsByCriteriaHandler implements CommandHandlerInterface
{
    public function __construct(
        private JobRepositoryInterface $jobRepository
    ) {
    }

    public function handle(CommandInterface $command): void
    {
        if (!$command instanceof DeleteJobsByCriteria) {
            throw new \InvalidArgumentException(sprintf(
                'Command must be instance of %s, %s given',
                DeleteJobsByCriteria::class,
                get_class($command)
            ));
        }

        $criteria = [];

        if (null !== $command->statuses) {
            $criteria['statuses'] = $command->statuses;
        }

        if (null !== $command->type) {
            $criteria['type'] = $command->type;
        }

        if (null !== $command->createdAfter) {
            $criteria['createdAfter'] = $command->createdAfter;
        }

        if (null !== $command->createdBefore) {
            $criteria['createdBefore'] = $command->createdBefore;
        }

        $this->jobRepository->deleteByCriteria($criteria);
    }
}
