<?php

declare(strict_types=1);

namespace App\Tests\Domain\Shared\Application\CommandHandler;

use App\Domain\Scraping\Domain\Model\ScrapingJob;
use App\Domain\Shared\Application\Command\DeleteJobsByCriteria;
use App\Domain\Shared\Application\CommandHandler\DeleteJobsByCriteriaHandler;
use App\Domain\Shared\Domain\Model\JobStatus;
use App\Tests\Domain\Shared\Adapter\InMemoryJobRepository;
use PHPUnit\Framework\TestCase;

class DeleteJobsByCriteriaHandlerTest extends TestCase
{
    private InMemoryJobRepository $repository;
    private DeleteJobsByCriteriaHandler $handler;

    protected function setUp(): void
    {
        $this->repository = new InMemoryJobRepository();
        $this->handler = new DeleteJobsByCriteriaHandler($this->repository);
    }

    public function test_it_deletes_jobs_by_status(): void
    {
        $job1 = new ScrapingJob('job-1', 'manga-1', 1.0, 'source-1');
        $job2 = new ScrapingJob('job-2', 'manga-1', 2.0, 'source-1');
        $job3 = new ScrapingJob('job-3', 'manga-1', 3.0, 'source-1');
        $job2->complete();
        $job3->complete();

        $this->repository->save($job1);
        $this->repository->save($job2);
        $this->repository->save($job3);

        $this->handler->handle(new DeleteJobsByCriteria(
            statuses: [JobStatus::COMPLETED]
        ));

        $this->assertNull($this->repository->get('job-2'));
        $this->assertNull($this->repository->get('job-3'));
        $this->assertNotNull($this->repository->get('job-1'));
    }

    public function test_it_deletes_jobs_by_type(): void
    {
        $job1 = new ScrapingJob('job-1', 'manga-1', 1.0, 'source-1');
        $job2 = new ScrapingJob('job-2', 'manga-1', 2.0, 'source-1');
        $this->repository->save($job1);
        $this->repository->save($job2);

        $this->handler->handle(new DeleteJobsByCriteria(
            type: 'scraping_job'
        ));

        $this->assertNull($this->repository->get('job-1'));
        $this->assertNull($this->repository->get('job-2'));
    }

    public function test_it_does_nothing_when_no_criteria_match(): void
    {
        $job = new ScrapingJob('job-1', 'manga-1', 1.0, 'source-1');
        $this->repository->save($job);

        $this->handler->handle(new DeleteJobsByCriteria(
            statuses: [JobStatus::FAILED]
        ));

        $this->assertNotNull($this->repository->get('job-1'));
    }
}
