<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Services\Sitemaps\SitemapBuildService;
use App\Services\Sitemaps\PublishedSitemapResolver;
use App\Services\Sitemaps\SitemapXmlRenderer;
use Illuminate\Http\Response;

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

    public function index(): Response
    {
        if ((bool) config('sitemaps.delivery.prefer_published_release', true)) {
            $published = $this->published->resolveIndex();
            if ($published !== null) {
                return $this->renderer->xmlResponse($published['content']);
            }
        }

        abort_unless((bool) config('sitemaps.delivery.fallback_to_live_build', true), 404);

        $built = $this->build->buildIndex(
            force: false,
            persist: (bool) config('sitemaps.refresh.build_on_request', true),
        );

        return $this->renderer->xmlResponse($built['content']);
    }

    public function show(string $name): Response
    {
        if ((bool) config('sitemaps.delivery.prefer_published_release', true)) {
            $published = $this->published->resolveNamed($name);
            if ($published !== null) {
                return $this->renderer->xmlResponse($published['content']);
            }
        }

        abort_unless((bool) config('sitemaps.delivery.fallback_to_live_build', true), 404);

        $built = $this->build->buildNamed(
            $name,
            force: false,
            persist: (bool) config('sitemaps.refresh.build_on_request', true),
        );

        abort_if($built === null, 404);

        return $this->renderer->xmlResponse($built['content']);
    }
}