<?php

declare(strict_types=1);

namespace App\Services\Academy;

use App\Models\AcademyLesson;
use App\Models\AcademyLessonProgress;
use App\Models\AcademyPromptTemplate;
use App\Models\AcademySavedPrompt;
use App\Models\User;

final class AcademyProgressService
{
    public function __construct(private readonly AcademyBadgeService $badges)
    {
    }

    public function markLessonComplete(User $user, AcademyLesson $lesson): AcademyLessonProgress
    {
        $progress = AcademyLessonProgress::query()->updateOrCreate(
            [
                'lesson_id' => $lesson->id,
                'user_id' => $user->id,
            ],
            [
                'completed_at' => now(),
            ],
        );

        $this->badges->syncForUser($user);

        return $progress;
    }

    public function savePrompt(User $user, AcademyPromptTemplate $prompt): AcademySavedPrompt
    {
        $saved = AcademySavedPrompt::query()->firstOrCreate([
            'prompt_template_id' => $prompt->id,
            'user_id' => $user->id,
        ]);

        $this->badges->syncForUser($user);

        return $saved;
    }

    public function unsavePrompt(User $user, AcademyPromptTemplate $prompt): void
    {
        AcademySavedPrompt::query()
            ->where('prompt_template_id', $prompt->id)
            ->where('user_id', $user->id)
            ->delete();

        $this->badges->syncForUser($user);
    }
}