<?php

declare(strict_types=1);

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Commerce\Catalog\Api\State;

use ApiPlatform\Metadata\CollectionOperationInterface;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use CpCreation\VitiCore\Commerce\Catalog\Api\Resource\CatalogProductResource;
use CpCreation\VitiCore\Commerce\Catalog\CatalogIdentity;
use CpCreation\VitiCore\Commerce\Catalog\CatalogProductProjector;
use CpCreation\VitiCore\Product\Model\Product;
use CpCreation\VitiCore\Product\Repository\ProductRepository;

/**
 * @implements ProviderInterface<CatalogProductResource>
 */
final readonly class CatalogProductProvider implements ProviderInterface
{
    public function __construct(
        private ProductRepository $productRepository,
        private CatalogIdentity $identity,
        private CatalogProductProjector $projector,
    ) {}

    public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
    {
        if ($operation instanceof CollectionOperationInterface) {
            return $this->projector->projectCollection($this->productRepository->findForCommerceCatalog());
        }

        $catalogId = $uriVariables['id'] ?? null;
        if (!\is_string($catalogId)) {
            return null;
        }

        $productId = $this->identity->parseProductId($catalogId);
        if (null === $productId) {
            return null;
        }

        $product = $this->productRepository->find($productId);
        if (!$product instanceof Product || !$this->canExpose($product)) {
            return null;
        }

        return $this->projector->project($product);
    }

    private function canExpose(Product $product): bool
    {
        return $product->isShop()
            && !$product->isDisabled()
            && !$product->isDeleted();
    }
}
