<?php

declare(strict_types=1);

namespace App\Module\Transport\Infrastructure\ApiPlatform\State\Provider;

use ApiPlatform\Doctrine\Orm\Paginator;
use ApiPlatform\Metadata\CollectionOperationInterface;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\Pagination\Pagination;
use ApiPlatform\State\ProviderInterface;
use App\Module\Transport\Domain\Entity\Carrier;
use App\Module\Transport\Domain\Repository\CarrierRepositoryInterface;
use Doctrine\ORM\Tools\Pagination\Paginator as DoctrinePaginator;
use Symfony\Component\DependencyInjection\Attribute\Autowire;

/**
 * Provider du repertoire transporteurs (M4, spec-back § 4.1 / § 4.2). Jumeau du
 * SupplierProvider (M2), simplifie : pas de cloisonnement par site (§ 2.3) et
 * aucune sous-collection a hydrater en liste (le contrat liste n'embarque que
 * qualimatCarrier, deja fetch-joine par le repository — § 2.11).
 *
 * Collection (GET /api/carriers) :
 *  - exclut par defaut les archives (is_archived = true) ET les soft-deletes ;
 *  - ?includeArchived=true reintegre les archives (soft-deletes toujours exclus) ;
 *  - ?archivedOnly=true n'expose QUE les archives (prioritaire sur includeArchived,
 *    aligne sur Client/Supplier/Provider — toggle « Voir les archives » ERP-173) ;
 *  - filtres ?search= (fuzzy name) et ?certificationType= (repetable) ;
 *  - tri par defaut name ASC ; pagination Hydra (regle n°13) + echappatoire
 *    ?pagination=false.
 *
 * Item (GET /api/carriers/{id}) : 404 si introuvable OU soft-delete. Les archives
 * restent consultables en detail.
 *
 * @implements ProviderInterface<Carrier>
 */
final class CarrierProvider implements ProviderInterface
{
    public function __construct(
        #[Autowire(service: 'App\Module\Transport\Infrastructure\Doctrine\DoctrineCarrierRepository')]
        private readonly CarrierRepositoryInterface $repository,
        private readonly Pagination $pagination,
    ) {}

    public function provide(Operation $operation, array $uriVariables = [], array $context = []): Carrier|iterable|Paginator|null
    {
        if ($operation instanceof CollectionOperationInterface) {
            return $this->provideCollection($operation, $context);
        }

        return $this->provideItem($uriVariables);
    }

    /**
     * @param array<string, mixed> $context
     *
     * @return list<Carrier>|Paginator<Carrier>
     */
    private function provideCollection(Operation $operation, array $context): array|Paginator
    {
        $filters            = $context['filters'] ?? [];
        $includeArchived    = $this->readBool($filters['includeArchived'] ?? false);
        $archivedOnly       = $this->readBool($filters['archivedOnly'] ?? false);
        $search             = $filters['search'] ?? null;
        $certificationTypes = $this->readStringList($filters['certificationType'] ?? []);

        $qb = $this->repository->createListQueryBuilder(
            $includeArchived,
            is_string($search) ? $search : null,
            $certificationTypes,
            $archivedOnly,
        );

        // Echappatoire ?pagination=false : collection complete (selects front).
        if (!$this->pagination->isEnabled($operation, $context)) {
            // @var list<Carrier> $carriers
            return $qb->getQuery()->getResult();
        }

        $limit  = $this->pagination->getLimit($operation, $context);
        $page   = max(1, $this->pagination->getPage($context));
        $offset = ($page - 1) * $limit;

        $qb->setFirstResult($offset)->setMaxResults($limit);

        // fetchJoinCollection: false — la seule jointure est un ManyToOne (sur),
        // pas une to-many : pas de besoin du mode collection du Paginator.
        return new Paginator(new DoctrinePaginator($qb->getQuery(), fetchJoinCollection: false));
    }

    /**
     * @param array<string, mixed> $uriVariables
     */
    private function provideItem(array $uriVariables): ?Carrier
    {
        $id = $uriVariables['id'] ?? null;
        if (!is_int($id) && !(is_string($id) && ctype_digit($id))) {
            return null;
        }

        $carrier = $this->repository->findById((int) $id);
        if (null === $carrier) {
            return null;
        }

        // Soft-delete : jamais expose (404). Les archives restent consultables.
        if (null !== $carrier->getDeletedAt()) {
            return null;
        }

        return $carrier;
    }

    private function readBool(mixed $raw): bool
    {
        if (is_bool($raw)) {
            return $raw;
        }

        return is_string($raw) && in_array(strtolower($raw), ['true', '1'], true);
    }

    /**
     * Normalise un filtre en liste de chaines (valeur unique ou ?key[]=a&key[]=b).
     *
     * @return list<string>
     */
    private function readStringList(mixed $raw): array
    {
        $values = is_array($raw) ? $raw : [$raw];

        $out = [];
        foreach ($values as $value) {
            if (is_string($value) && '' !== trim($value)) {
                $out[] = trim($value);
            }
        }

        return $out;
    }
}
