<?php

declare(strict_types=1);

namespace App\Services\Sitemaps\Builders;

use App\Models\Page;
use App\Services\Sitemaps\AbstractSitemapBuilder;
use App\Services\Sitemaps\SitemapUrlBuilder;
use DateTimeInterface;

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

    public function name(): string
    {
        return 'static-pages';
    }

    public function items(): array
    {
        $items = [
            $this->urls->staticRoute('/'),
            $this->urls->staticRoute('/academy'),
            $this->urls->staticRoute('/academy/pricing'),
            $this->urls->staticRoute('/web-stories'),
            $this->urls->staticRoute('/faq'),
            $this->urls->staticRoute('/rules-and-guidelines'),
            $this->urls->staticRoute('/privacy-policy'),
            $this->urls->staticRoute('/terms-of-service'),
            $this->urls->staticRoute('/staff'),
        ];

        $marketingPages = Page::query()
            ->published()
            ->whereIn('slug', ['about', 'help'])
            ->get()
            ->keyBy('slug');

        if ($marketingPages->has('about')) {
            $items[] = $this->urls->page($marketingPages['about'], '/about');
        }

        if ($marketingPages->has('help')) {
            $items[] = $this->urls->page($marketingPages['help'], '/help');
        }

        $excluded = array_values((array) config('sitemaps.static_page_excluded_slugs', []));

        foreach (Page::query()->published()->whereNotIn('slug', $excluded)->orderBy('slug')->get() as $page) {
            $items[] = $this->urls->page($page, '/pages/' . $page->slug);
        }

        return $items;
    }

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