<?php

namespace App\Http\Controllers;

use App\Models\ImportedJob;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Schema;
use Throwable;

class LandingController extends Controller
{
    public function __invoke(): View
    {
        $homepageJobs = $this->homepageJobs();

        return view('welcome', [
            'homepageJobs' => $homepageJobs,
            'homepageJobCount' => $this->activeJobCount($homepageJobs->count()),
        ]);
    }

    /**
     * @return Collection<int, ImportedJob>
     */
    private function homepageJobs(): Collection
    {
        try {
            if (! Schema::hasTable('imported_jobs')) {
                return collect();
            }

            return ImportedJob::query()
                ->with('source')
                ->active()
                ->latest('posted_at')
                ->latest('id')
                ->limit(8)
                ->get();
        } catch (Throwable $exception) {
            report($exception);

            return collect();
        }
    }

    private function activeJobCount(int $fallback = 0): int
    {
        try {
            if (! Schema::hasTable('imported_jobs')) {
                return $fallback;
            }

            return ImportedJob::query()->active()->count();
        } catch (Throwable $exception) {
            report($exception);

            return $fallback;
        }
    }
}
