<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\Commerce\Catalog;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Glide\GenerateUri;
use CpCreation\VitiCore\Commerce\Catalog\Api\Resource\CatalogMedia;
use CpCreation\VitiCore\Commerce\Catalog\Api\Resource\CatalogMediaRendition;
use CpCreation\VitiCore\Commerce\Catalog\Api\Resource\CatalogMediaSource;
use CpCreation\VitiCore\Media\Model\Image;
use Symfony\Component\Routing\Exception\ExceptionInterface as RoutingExceptionInterface;

final readonly class CatalogMediaProjector
{
    public function __construct(
        private CatalogIdentity $identity,
        private GenerateUri $generateUri,
    ) {}

    /**
     * @param array<string, string> $altByLocale
     */
    public function project(
        Image $image,
        string $scope,
        string $role,
        int $position,
        array $altByLocale,
    ): ?CatalogMedia {
        $path = $image->getPath();
        if (!\is_string($path) || '' === mb_trim($path) || !$image->isPublished()) {
            return null;
        }

        $renditions = [];
        foreach ([
            ['feed', 1200, 1200],
            ['thumbnail', 400, 400],
        ] as [$name, $width, $height]) {
            try {
                $url = ($this->generateUri)($path, 'image', [
                    'fm' => 'jpg',
                    'q' => 85,
                    'fit' => 'contain',
                    'bg' => 'ffffff',
                    'w' => $width,
                    'h' => $height,
                ]);
            } catch (\RuntimeException|RoutingExceptionInterface) {
                continue;
            }

            $renditions[] = new CatalogMediaRendition($name, $url, 'jpeg', $width, $height);
        }

        return new CatalogMedia(
            id: $this->identity->mediaId($image->getId()),
            source_id: $image->getId()->toString(),
            source_scope: $scope,
            role: $role,
            position: $position,
            alt_by_locale: $altByLocale,
            source: new CatalogMediaSource(
                mime_type: $image->getMimeType(),
                width: $image->getWidth(),
                height: $image->getHeight(),
                size_bytes: $image->getSize(),
            ),
            renditions: $renditions,
        );
    }
}
