<?php

declare(strict_types=1);

namespace App\Services\Sitemaps\Builders;

use App\Models\Tag;
use App\Services\Sitemaps\AbstractSitemapBuilder;
use App\Services\Sitemaps\SitemapUrl;
use App\Services\Sitemaps\SitemapUrlBuilder;
use DateTimeInterface;

final class TagsSitemapBuilder extends AbstractSitemapBuilder
{
    public function __construct(private readonly SitemapUrlBuilder $urls)
    {
    }

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

    public function items(): array
    {
        return Tag::query()
            ->where('is_active', true)
            ->where('usage_count', '>', 0)
            ->whereHas('artworks', fn ($query) => $query->public()->published())
            ->orderByDesc('usage_count')
            ->orderBy('slug')
            ->get()
            ->map(fn (Tag $tag): SitemapUrl => $this->urls->tag($tag))
            ->values()
            ->all();
    }

    public function lastModified(): ?DateTimeInterface
    {
        return $this->dateTime(Tag::query()
            ->where('is_active', true)
            ->where('usage_count', '>', 0)
            ->max('updated_at'));
    }
}