<?php

namespace App\Services;

use App\Models\ImportedJob;
use App\Models\User;
use Illuminate\Support\Collection;

class ApplicantDashboardService
{
    /**
     * @param  Collection<int, ImportedJob>  $rankedJobs
     * @return array<string, int>
     */
    public function analytics(User $user, Collection $rankedJobs): array
    {
        $savedCount = $user->savedJobs()->count();
        $applications = $user->applications();
        $resumeReport = $user->resumeReport;

        return [
            'matched_jobs' => $rankedJobs->count(),
            'high_matches' => $rankedJobs->filter(fn (ImportedJob $job): bool => (int) $job->match_score >= 75)->count(),
            'saved_jobs' => $savedCount,
            'applied_jobs' => (clone $applications)->count(),
            'follow_up_needed' => (clone $applications)->where('status', 'follow_up_needed')->count(),
            'ats_score' => (int) ($resumeReport?->ats_score ?? 0),
            'remote_readiness_score' => (int) ($resumeReport?->remote_readiness_score ?? 0),
        ];
    }

    public function profileCompletion(User $user): int
    {
        $user->loadMissing(['profile', 'questionnaireResponse', 'resumeReport']);

        $checks = [
            $user->hasCompletedQuestionnaire(),
            $user->hasUnlockedAccess(),
            $user->hasUploadedResume(),
            $user->hasAnalyzedResume(),
            $user->hasCompletedProfile(),
            filled($user->profile?->skills),
            filled($user->profile?->preferred_roles),
            filled($user->profile?->preferred_categories),
            filled($user->profile?->salary_min),
            filled($user->profile?->timezone),
        ];

        $completed = collect($checks)->filter()->count();

        return (int) round(($completed / count($checks)) * 100);
    }

    /**
     * @return array{label: string, url: string, tone: string}
     */
    public function nextAction(User $user): array
    {
        if (! $user->hasCompletedQuestionnaire()) {
            return ['label' => 'Complete questionnaire', 'url' => route('questionnaire.show'), 'tone' => 'warning'];
        }

        if (! $user->hasUnlockedAccess()) {
            return ['label' => 'Unlock access', 'url' => route('payment.checkout'), 'tone' => 'warning'];
        }

        if (! $user->hasUploadedResume() || ! $user->hasAnalyzedResume()) {
            return ['label' => 'Finish resume analysis', 'url' => route('resume.show'), 'tone' => 'warning'];
        }

        if (! $user->hasCompletedProfile()) {
            return ['label' => 'Complete profile', 'url' => route('profile.edit'), 'tone' => 'warning'];
        }

        return ['label' => 'View best matches', 'url' => route('jobs.index'), 'tone' => 'success'];
    }
}
