<?php

namespace App\Http\Controllers\Site;

use App\Http\Controllers\Controller;
use App\Models\Download;
use App\Models\JobListing;
use App\Models\NewsPost;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Cache;
use Spatie\Sitemap\Sitemap;
use Spatie\Sitemap\Tags\Url;

class SitemapController extends Controller
{
    public function __invoke(): Response
    {
        $key = config('hillcrest.cache.sitemap_key');
        $ttl = max(300, (int) config('hillcrest.cache.sitemap_ttl_seconds'));

        $xml = Cache::remember($key, now()->addSeconds($ttl), function (): string {
            $sitemap = Sitemap::create();

            $sitemap->add(Url::create(route('home')));
            $sitemap->add(Url::create(url('/about')));
            $sitemap->add(Url::create(url('/services')));
            $sitemap->add(Url::create(url('/who-we-support')));
            $sitemap->add(Url::create(url('/referral')));
            $sitemap->add(Url::create(url('/testimonials')));
            $sitemap->add(Url::create(route('news.index')));
            $sitemap->add(Url::create(route('careers.index')));
            $sitemap->add(Url::create(route('downloads.index')));
            $sitemap->add(Url::create(url('/contact')));
            $sitemap->add(Url::create(url('/privacy')));

            foreach (NewsPost::query()->published()->get() as $post) {
                $sitemap->add(Url::create(route('news.show', $post)));
            }

            foreach (JobListing::query()->openPublic()->get() as $job) {
                $sitemap->add(Url::create(route('careers.show', $job)));
            }

            foreach (Download::query()->published()->get() as $download) {
                $sitemap->add(Url::create(route('downloads.file', $download)));
            }

            return $sitemap->render();
        });

        return response($xml, 200)->header('Content-Type', 'application/xml');
    }
}
