<?php

declare(strict_types=1);

namespace App\Services\Academy;

use App\Models\AcademyCourse;
use App\Models\AcademyCourseLesson;

final class AcademyCourseLessonOrderingService
{
    public function syncCourse(AcademyCourse|int $course): void
    {
        $courseId = $course instanceof AcademyCourse ? (int) $course->id : (int) $course;

        if ($courseId < 1) {
            return;
        }

        AcademyCourseLesson::query()
            ->with('lesson:id,lesson_number,course_order')
            ->where('course_id', $courseId)
            ->orderBy('order_num')
            ->orderBy('id')
            ->get()
            ->values()
            ->each(function (AcademyCourseLesson $courseLesson, int $index): void {
                $pivotOrder = $index;
                $lessonOrder = $index + 1;

                if ((int) ($courseLesson->order_num ?? 0) !== $pivotOrder) {
                    $courseLesson->forceFill([
                        'order_num' => $pivotOrder,
                    ])->save();
                }

                if ($courseLesson->lesson === null) {
                    return;
                }

                if ((int) ($courseLesson->lesson->course_order ?? 0) === $lessonOrder
                    && (int) ($courseLesson->lesson->lesson_number ?? 0) === $lessonOrder) {
                    return;
                }

                $courseLesson->lesson->forceFill([
                    'course_order' => $lessonOrder,
                    'lesson_number' => $lessonOrder,
                ])->save();
            });
    }
}