<?php

declare(strict_types=1);

namespace App\Domain\Shared\Infrastructure\ApiPlatform\State\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Domain\Shared\Application\Query\ListJobsQuery;
use App\Domain\Shared\Application\QueryHandler\ListJobsQueryHandler;
use App\Domain\Shared\Domain\Model\JobStatus;
use App\Domain\Shared\Infrastructure\ApiPlatform\Resource\GetJobListResource;
use ApiPlatform\State\Pagination\ArrayPaginator;

readonly class GetJobListStateProvider implements ProviderInterface
{
    public function __construct(
        private ListJobsQueryHandler $handler
    ) {
    }

    public function provide(Operation $operation, array $uriVariables = [], array $context = []): ArrayPaginator
    {
        $filters = $context['filters'] ?? [];

        $statuses = null;
        if (isset($filters['status'])) {
            if (is_array($filters['status'])) {
                // Cas où status est passé en format tableau: status[]=pending&status[]=in_progress
                $statusValues = $filters['status'];
            } else {
                // Cas où status est passé comme une chaîne séparée par des virgules: status=pending,in_progress
                $statusValues = explode(',', $filters['status']);
            }

            $statuses = [];
            foreach ($statusValues as $statusValue) {
                try {
                    $statuses[] = JobStatus::from($statusValue);
                } catch (\ValueError $e) {
                    // Ignorer les valeurs invalides
                    continue;
                }
            }

            // Si aucun statut valide n'est trouvé, on met $statuses à null
            if (empty($statuses)) {
                $statuses = null;
            }
        }

        $query = new ListJobsQuery(
            statuses: $statuses,
            type: $filters['type'] ?? null,
            createdAfter: isset($filters['createdAfter']) ? new \DateTimeImmutable($filters['createdAfter']) : null,
            createdBefore: isset($filters['createdBefore']) ? new \DateTimeImmutable($filters['createdBefore']) : null,
            page: (int) ($filters['page'] ?? 1),
            limit: (int) ($filters['limit'] ?? 20),
            sortBy: $filters['sortBy'] ?? 'createdAt',
            sortOrder: $filters['sortOrder'] ?? 'DESC'
        );

        $response = $this->handler->handle($query);

        return new ArrayPaginator(
            array_map(
                fn ($job) => GetJobListResource::fromJob($job),
                $response->items
            ),
            0,
            $response->total
        );
    }
}
