<?php

namespace App\Http\Controllers;

use App\Models\Application;
use App\Models\ImportedJob;
use App\Services\ApplicantDashboardService;
use App\Services\JobMatchingService;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;

class ApplicantDashboardController extends Controller
{
    public function __invoke(
        Request $request,
        ApplicantDashboardService $dashboardService,
        JobMatchingService $matchingService
    ): View {
        Gate::authorize('viewAny', ImportedJob::class);

        $user = $request->user()->load(['profile', 'questionnaireResponse', 'resumeReport']);
        $rankedJobs = $matchingService->rankedJobsFor($user);

        return view('applicant.dashboard', [
            'user' => $user,
            'profileCompletion' => $dashboardService->profileCompletion($user),
            'analytics' => $dashboardService->analytics($user, $rankedJobs),
            'topJobs' => $rankedJobs->take(4),
            'savedJobIds' => $user->savedJobs()->pluck('imported_job_id')->all(),
            'recentApplications' => Application::query()
                ->with('importedJob')
                ->where('user_id', $user->id)
                ->latest('applied_at')
                ->limit(5)
                ->get(),
            'nextAction' => $dashboardService->nextAction($user),
        ]);
    }
}
