<?php

declare(strict_types=1);

namespace App\Services\Sitemaps\Builders;

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

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

    public function name(): string
    {
        return 'academy-lessons';
    }

    public function items(): array
    {
        if (! (bool) config('academy.enabled', true)) {
            return [];
        }

        $items = [$this->urls->staticRoute('/academy/lessons')];

        $details = AcademyLesson::query()
            ->active()
            ->published()
            ->orderBy('id')
            ->cursor()
            ->map(fn (AcademyLesson $lesson): SitemapUrl => $this->urls->staticRoute('/academy/lessons/' . $lesson->slug, $lesson->updated_at ?? $lesson->published_at))
            ->values()
            ->all();

        return array_merge($items, $details);
    }

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