<?php

namespace App\Shared\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class SeoController extends AbstractController
{
    #[Route('/robots.txt', name: 'seo_robots', methods: ['GET'])]
    public function robots(Request $request): Response
    {
        if ($this->isStaging($request)) {
            $body = "User-agent: *\nDisallow: /\n";
        } else {
            $base = $request->getSchemeAndHttpHost();
            $body = "User-agent: *\n"
                . "Disallow: /admin\n"
                . "Disallow: /api\n"
                . "Allow: /\n\n"
                . "Sitemap: {$base}/sitemap.xml\n";
        }

        return new Response($body, Response::HTTP_OK, ['Content-Type' => 'text/plain; charset=UTF-8']);
    }

    #[Route('/sitemap.xml', name: 'seo_sitemap', methods: ['GET'])]
    public function sitemap(Request $request): Response
    {
        $base = $request->getSchemeAndHttpHost();
        $xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n"
            . '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n"
            . '  <url>' . "\n"
            . "    <loc>{$base}/</loc>\n"
            . '    <changefreq>weekly</changefreq>' . "\n"
            . '    <priority>1.0</priority>' . "\n"
            . '  </url>' . "\n"
            . '</urlset>' . "\n";

        return new Response($xml, Response::HTTP_OK, ['Content-Type' => 'application/xml; charset=UTF-8']);
    }

    private function isStaging(Request $request): bool
    {
        $host = $request->getHost();

        return str_ends_with($host, '.ddev.site')
            || str_contains($host, 'localhost')
            || str_starts_with($host, '127.0.0.1');
    }
}
