<?php

namespace App\Console\Commands;

use App\Models\Entry;
use App\Models\News;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Spatie\Sitemap\Sitemap;
use Spatie\Sitemap\Tags\Url;

#[Signature('sitemap:generate')]
class GenerateSitemap extends Command
{
    public function handle()
    {
        $sitemap = Sitemap::create()
            ->add(Url::create('/')->setPriority(1.0)->setChangeFrequency(Url::CHANGE_FREQUENCY_DAILY))
            ->add(Url::create('/database')->setPriority(0.8)->setChangeFrequency(Url::CHANGE_FREQUENCY_DAILY))
            ->add(Url::create('/news')->setPriority(0.7)->setChangeFrequency(Url::CHANGE_FREQUENCY_DAILY))
            ->add(Url::create(route('tools.patcher'))->setPriority(0.2)->setChangeFrequency(Url::CHANGE_FREQUENCY_MONTHLY) )
            ->add(Url::create(route('tools.hash'))->setPriority(0.2)->setChangeFrequency(Url::CHANGE_FREQUENCY_MONTHLY) )
        ;

        Entry::cursor()->each(function (Entry $entry) use ($sitemap) {

            if (empty($entry->type) || empty($entry->slug)) {
                return;
            }

            try {
                $url = route('entries.show', [
                    'section' => $entry->type,
                    'entry'   => $entry->slug
                ]);

                $sitemap->add(
                    Url::create($url)
                        ->setLastModificationDate($entry->updated_at)
                        ->setChangeFrequency(Url::CHANGE_FREQUENCY_WEEKLY)
                        ->setPriority(0.8)
                );
            } catch (\Exception $e) {
                logger()->error("Sitemap error for entry :  {$entry->id}: " . $e->getMessage());
            }
        });

        News::cursor()->each(function (News $entry) use ($sitemap) {

            if (empty($entry->type) || empty($entry->slug)) {
                return;
            }

            try {
                $url = route('news.show', ['news' => $entry]);

                $sitemap->add(
                    Url::create($url)
                        ->setLastModificationDate($entry->updated_at)
                        ->setChangeFrequency(Url::CHANGE_FREQUENCY_WEEKLY)
                        ->setPriority(0.8)
                );
            } catch (\Exception $e) {
                logger()->error("Sitemap error for news :  {$entry->id}: " . $e->getMessage());
            }
        });

        $sitemap->writeToFile(public_path('sitemap.xml'));
        $this->info('Generated sitemap');
    }
}
