<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Services\Sitemaps\PublishedSitemapResolver;
use App\Services\Sitemaps\SitemapXmlRenderer;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Illuminate\Http\Response;

final class SitemapController extends Controller
{
    public function __construct(
        private readonly PublishedSitemapResolver $published,
        private readonly SitemapXmlRenderer $renderer,
    ) {
    }

    public function index(): Response|BinaryFileResponse
    {
        // 1. Static file written by the build/generate commands.
        //    On production nginx serves this directly via try_files without reaching PHP.
        //    On dev / misconfigured servers we stream it with sendfile — no RAM load.
        $path = public_path('sitemap.xml');
        if (file_exists($path)) {
            return $this->xmlFileResponse($path);
        }

        // 2. Published release (release management pipeline fallback).
        $published = $this->published->resolveIndex();
        if ($published !== null) {
            return $this->renderer->xmlResponse($published['content']);
        }

        throw new NotFoundHttpException();
    }

    public function show(string $name): Response|BinaryFileResponse
    {
        // 1. Static file.
        $path = public_path('sitemaps/' . $name . '.xml');
        if (file_exists($path)) {
            return $this->xmlFileResponse($path);
        }

        // 2. Published release.
        $published = $this->published->resolveNamed($name);
        if ($published !== null) {
            return $this->renderer->xmlResponse($published['content']);
        }

        throw new NotFoundHttpException();
    }

    private function xmlFileResponse(string $absolutePath): BinaryFileResponse
    {
        return response()->file($absolutePath, [
            'Content-Type'  => 'application/xml; charset=UTF-8',
            'Cache-Control' => 'public, max-age=' . max(60, (int) config('sitemaps.cache_ttl_seconds', 900)),
        ]);
    }
}