<?php

declare(strict_types=1);

namespace App\Http\Controllers\Academy;

use App\Http\Controllers\Controller;
use App\Models\AcademyCourse;
use App\Services\Academy\AcademyProgressService;
use App\Services\Academy\AcademyCourseProgressService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

final class AcademyCourseEnrollmentController extends Controller
{
    public function __construct(
        private readonly AcademyCourseProgressService $progress,
        private readonly AcademyProgressService $academyProgress,
    ) {
    }

    public function start(Request $request, AcademyCourse $course): RedirectResponse
    {
        abort_unless((bool) config('academy.enabled', true), 404);
        abort_unless($course->isPublished(), 404);

        $this->academyProgress->startCourse($request->user(), (int) $course->id, $request);
        $continueLesson = $this->progress->getContinueLesson($request->user(), $course);

        if ($continueLesson?->lesson) {
            return redirect()->route('academy.courses.lessons.show', ['course' => $course->slug, 'lesson' => $continueLesson->lesson->slug]);
        }

        return redirect()->route('academy.courses.show', ['course' => $course->slug]);
    }
}