<?php

namespace App\Modules\Pilkades\Http\Controllers\Public;

use App\Http\Controllers\Controller;
use App\Modules\Pilkades\Repositories\Contracts\DesaRepositoryInterface;
use App\Modules\Pilkades\Services\LandingPageCacheService;
use App\Modules\Pilkades\Services\VisitorTrackingService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\Response;

class LandingPageController extends Controller
{
    public function __construct(
        protected DesaRepositoryInterface $desaRepository,
        protected VisitorTrackingService $visitorTracking,
        protected LandingPageCacheService $landingPageCache,
    ) {}

    public function show(Request $request, string $kabupaten, string $kecamatan, string $desa): View|Response
    {
        $cacheKey = $this->landingPageCache->key($kabupaten, $kecamatan, $desa);

        $data = Cache::remember($cacheKey, now()->addMinutes(10), function () use ($kabupaten, $kecamatan, $desa) {
            $desaModel = $this->desaRepository->findBySlug($kabupaten, $kecamatan, $desa);

            if (! $desaModel || ! $desaModel->isPublished()) {
                return null;
            }

            $desaModel->load([
                'kecamatan.kabupaten',
                'landingPage',
                'countdown',
                'banners' => fn ($q) => $q->where('is_active', true)->orderBy('urutan'),
                'candidates' => fn ($q) => $q->where('status', 'aktif')->orderBy('nomor_urut'),
                'candidates.profile',
                'candidates.programs',
                'candidates.gallery.media',
                'candidates.videos',
                'faqs' => fn ($q) => $q->where('is_active', true)->orderBy('urutan'),
                'contacts' => fn ($q) => $q->orderBy('urutan'),
                'tpsList',
            ]);

            return $desaModel;
        });

        abort_if(! $data, 404);

        $this->visitorTracking->record($request, $data->id);

        return view('pilkades::public.landing.index', ['desa' => $data]);
    }
}
