<?php

namespace TechnoArtisan\FilamentCms\Commands;

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

use function config;
use function public_path;

class SitemapGeneratorCommand extends Command
{
    public $signature   = 'filament-cms:generate-sitemap';
    public $description = 'generate a specialized sitemap.xml';

    public function handle(): int
    {
        $this->comment('generating sitemap(s)...');

        $this->comment('generating (de)...');
        $siteMapDe = 'sitemap-de.xml';
        SitemapGenerator::create(config('app.url') . '/de')
                        ->hasCrawled(function (Url $url) {
                            if ($url->segment(1) === 'en') {
                                return null;
                            }

                            return $url;
                        })
                        ->writeToFile(public_path($siteMapDe));

        $this->comment('generating (en)...');
        $siteMapEn = 'sitemap-en.xml';
        SitemapGenerator::create(config('app.url') . '/en')
                        ->hasCrawled(function (Url $url) {
                            if ($url->segment(1) === 'de') {
                                return null;
                            }

                            return $url;
                        })
                        ->writeToFile(public_path($siteMapEn));

        $this->comment('generating (index)...');
        SitemapIndex::create()
                    ->add('/' . $siteMapDe)
                    ->add('/' . $siteMapEn)
                    ->writeToFile(public_path('sitemap.xml'));

        $this->comment('done.');

        return self::SUCCESS;
    }
}
