<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Spatie\Sitemap\Sitemap;
use Spatie\Sitemap\Tags\Url;

class GenerateSitemap extends Command
{
    protected $signature = 'sitemap:generate';

    protected $description = 'Generate the sitemap dynamically using config routes';

    private const PRIORITY = 0.5;

    private const CHANGE_FREQUENCY = 'weekly';

    public function handle()
    {
        $sitemap = Sitemap::create();
        $routes = config('routes.web', []);

        foreach ($routes as $route) {
            if (isset($route['path'])) {
                $this->info('Adding '.$route['path'].' to sitemap.');
                $sitemap->add(Url::create($route['path'])
                    ->setPriority($route['priority'] ?? static::PRIORITY)
                    ->setLastModificationDate($route['last_modified'] ?? now())
                    ->setChangeFrequency($route['frequency'] ?? static::CHANGE_FREQUENCY));
            }
        }

        $sitemap->writeToFile(public_path('sitemap.xml'));
        $this->info('Sitemap has been successfully generated!');
    }
}
