<?php

declare(strict_types=1);

namespace App\Services\Sitemaps\Builders;

use App\Models\Category;
use App\Services\ContentTypes\ContentTypeSlugResolver;
use App\Services\Sitemaps\AbstractSitemapBuilder;
use App\Services\Sitemaps\SitemapUrlBuilder;
use DateTimeInterface;

final class CategoriesSitemapBuilder extends AbstractSitemapBuilder
{
    public function __construct(
        private readonly SitemapUrlBuilder $urls,
        private readonly ContentTypeSlugResolver $contentTypeResolver,
    )
    {
    }

    public function name(): string
    {
        return 'categories';
    }

    public function items(): array
    {
        $items = [$this->urls->categoryDirectory()];

        $contentTypes = $this->contentTypeResolver->dynamicSitemapContentTypes();

        foreach ($contentTypes as $contentType) {
            $items[] = $this->urls->contentType($contentType);
        }

        $contentTypeIds = $contentTypes->pluck('id')->filter()->values();

        $categories = Category::query()
            ->with('contentType')
            ->active()
            ->when($contentTypeIds->isNotEmpty(), fn ($query) => $query->whereIn('content_type_id', $contentTypeIds->all()))
            ->orderBy('content_type_id')
            ->orderBy('parent_id')
            ->orderBy('sort_order')
            ->orderBy('name')
            ->get();

        foreach ($categories as $category) {
            $items[] = $this->urls->category($category);
        }

        return $items;
    }

    public function lastModified(): ?DateTimeInterface
    {
        return $this->dateTime(Category::query()
            ->active()
            ->max('updated_at'));
    }
}