<?php

declare(strict_types=1);

namespace App\Application\Website;

use App\Framework\Attributes\Route;
use App\Framework\Http\Headers;
use App\Framework\Http\HttpResponse;
use App\Framework\Meta\StaticPageMetaResolver;
use App\Framework\Router\Result\ViewResult;
use App\Framework\Router\WebRoutes;
use App\Framework\Sitemap\SitemapGenerator;

final readonly class ShowSitemap
{
    public function __construct(
        private SitemapGenerator $sitemapGenerator,
    ) {
    }

    private function generateSitemapXml(): string
    {
        $xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
        $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";

        foreach ($this->sitemapGenerator->generateFromRoutes() as $entry) {
            $xml .= '  ' . $entry->toXml() . "\n";
        }

        $xml .= '</urlset>';

        return $xml;
    }

    #[Route(path: '/sitemap.xml', name: WebRoutes::SITEMAP)]
    public function __invoke(): HttpResponse
    {
        $xml = $this->generateSitemapXml();

        return new HttpResponse(
            headers: new Headers(['Content-Type' => 'application/xml']),
            body   : $xml
        );

        #https://www.flowmatters.com/blog/how-to-improve-your-seo-by-optimising-a-dynamic-sitemap-xml-gz-using-php/
    }

    #[Route(path: '/sitemap', name: WebRoutes::SITEMAP_READABLE)]
    public function sitemap(): ViewResult
    {
        return new ViewResult(
            'sitemap',
            new StaticPageMetaResolver('Sitemap', 'Die Sitemap')()
        );
    }
}
