<?php

declare(strict_types=1);

namespace App\Services\Sitemaps;

final class SitemapIndexService
{
    public function __construct(
        private readonly SitemapRegistry $registry,
        private readonly SitemapShardService $shards,
    ) {
    }

    /**
     * @return list<SitemapIndexItem>
     */
    public function items(?array $families = null): array
    {
        $items = [];

        foreach ($families ?? (array) config('sitemaps.enabled', []) as $name) {
            $builder = $this->registry->get((string) $name);

            if ($builder === null) {
                continue;
            }

            $items[] = new SitemapIndexItem(
                url('/sitemaps/' . $this->shards->rootEntryName($builder) . '.xml'),
                $builder->lastModified(),
            );
        }

        return $items;
    }

    /**
     * @return list<SitemapIndexItem>
     */
    public function itemsForBuilder(SitemapBuilder $builder): array
    {
        if ($builder instanceof ShardableSitemapBuilder && $this->shards->shardCount($builder) > 1) {
            $items = [];

            foreach (range(1, $this->shards->shardCount($builder)) as $shard) {
                $items[] = new SitemapIndexItem(
                    url('/sitemaps/' . $this->shards->canonicalShardName($builder->name(), $shard) . '.xml'),
                    $builder->lastModifiedForShard($shard),
                );
            }

            return $items;
        }

        return [new SitemapIndexItem(
            url('/sitemaps/' . $this->shards->rootEntryName($builder) . '.xml'),
            $builder->lastModified(),
        )];
    }
}