<?php

declare(strict_types=1);

namespace App\Services\Academy;

use App\Models\AcademyBadge;
use App\Models\AcademySavedPrompt;
use App\Models\User;

final class AcademyBadgeService
{
    public function syncForUser(User $user): void
    {
        if (! (bool) config('academy.badges_enabled', true)) {
            return;
        }

        $savedPromptCount = AcademySavedPrompt::query()->where('user_id', $user->id)->count();
        $completedLessons = $user->academyLessonProgress()->whereNotNull('completed_at')->count();

        foreach (AcademyBadge::query()->active()->get() as $badge) {
            $rules = (array) ($badge->rules ?? []);

            if (isset($rules['complete_lessons']) && $completedLessons < (int) $rules['complete_lessons']) {
                continue;
            }

            if (isset($rules['save_prompts']) && $savedPromptCount < (int) $rules['save_prompts']) {
                continue;
            }

            $user->academyBadges()->syncWithoutDetaching([
                $badge->id => ['awarded_at' => now()],
            ]);
        }
    }
}