<?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;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Provider\LocaleProvider;
use CpCreation\VitiCore\Commerce\Catalog\Api\Resource\CatalogInstanceResource;
use CpCreation\VitiCore\Commerce\Catalog\Configuration\CatalogIntegrationConfiguration;
use CpCreation\VitiCore\Commerce\Catalog\Configuration\CatalogWebhookEndpointResolver;

final readonly class CatalogInstanceProjector
{
    public function __construct(
        private CatalogIdentity $identity,
        private CatalogIntegrationConfiguration $configuration,
        private CatalogWebhookEndpointResolver $webhookEndpointResolver,
        private CatalogSellerProjector $sellerProjector,
        private LocaleProvider $localeProvider,
    ) {}

    public function project(?\DateTimeImmutable $now = null): CatalogInstanceResource
    {
        $capabilities = [
            'products.read',
            'changes.read',
            'media.glide',
        ];
        if ($this->webhookEndpointResolver->isReady()) {
            $capabilities[] = 'webhook.notifications';
        }

        return new CatalogInstanceResource(
            schema_version: CatalogContract::SCHEMA_VERSION,
            instance_id: $this->identity->instanceId(),
            generated_at: $this->timestamp($now ?? new \DateTimeImmutable()),
            seller: $this->sellerProjector->project(),
            locales: $this->locales(),
            currency: $this->configuration->currency(),
            capabilities: $capabilities,
        );
    }

    /**
     * @return list<string>
     */
    private function locales(): array
    {
        $defaultLocale = mb_trim($this->localeProvider->getDefaultLocale());
        $locales = [];
        foreach ($this->localeProvider->getLocales() as $locale) {
            if (!\is_string($locale)) {
                continue;
            }

            $locale = mb_trim($locale);
            if ('' !== $locale && $locale !== $defaultLocale) {
                $locales[$locale] = true;
            }
        }
        $locales = array_keys($locales);
        sort($locales);

        return '' !== $defaultLocale ? [$defaultLocale, ...$locales] : $locales;
    }

    private function timestamp(\DateTimeInterface $date): string
    {
        return \DateTimeImmutable::createFromInterface($date)
            ->setTimezone(new \DateTimeZone('UTC'))
            ->format(\DATE_ATOM);
    }
}
