<?php

declare(strict_types=1);

namespace App\Domain\Shared\Application\QueryHandler;

use App\Domain\Shared\Application\Query\ListJobsQuery;
use App\Domain\Shared\Application\Response\JobListResponse;
use App\Domain\Shared\Domain\Contract\QueryHandlerInterface;
use App\Domain\Shared\Domain\Contract\QueryInterface;
use App\Domain\Shared\Domain\Contract\ResponseInterface;
use App\Domain\Shared\Domain\Contract\JobRepositoryInterface;

readonly class ListJobsQueryHandler implements QueryHandlerInterface
{
    public function __construct(
        private JobRepositoryInterface $jobRepository
    ) {
    }

    public function handle(QueryInterface $query): ResponseInterface
    {
        if (!$query instanceof ListJobsQuery) {
            throw new \InvalidArgumentException(sprintf(
                'Query must be instance of %s, %s given',
                ListJobsQuery::class,
                get_class($query)
            ));
        }

        $criteria = [
            'statuses' => $query->statuses,
            'type' => $query->type,
            'createdAfter' => $query->createdAfter,
            'createdBefore' => $query->createdBefore,
            'sortBy' => $query->sortBy,
            'sortOrder' => $query->sortOrder,
            'offset' => $query->getOffset(),
            'limit' => $query->limit
        ];

        $jobs = $this->jobRepository->findByCriteria($criteria);
        $total = $this->jobRepository->countByCriteria($criteria);

        return JobListResponse::fromJobs(
            jobs: $jobs,
            total: $total,
            page: $query->page,
            limit: $query->limit
        );
    }
}
