<?php

namespace App\Services;

use App\Models\Course;
use App\Models\CourseEnrollment;
use App\Models\User;
use Illuminate\Support\Collection;

class UserCourseStatusService
{
    public function syncUser(User $user): bool
    {
        return $user->syncCourseAccessStatus();
    }

    public function syncUsersByIds($userIds): void
    {
        $ids = Collection::make($userIds)
            ->filter()
            ->unique()
            ->values();

        if ($ids->isEmpty()) {
            return;
        }

        User::whereIn('id', $ids)->get()->each(function (User $user) {
            $user->syncCourseAccessStatus();
        });
    }

    public function syncCourseParticipants(Course $course, array $extraUserIds = []): void
    {
        $course->loadMissing('enrollments:id,course_id,student_id');

        $userIds = $course->enrollments
            ->pluck('student_id')
            ->push($course->teacher_id)
            ->merge($extraUserIds);

        $this->syncUsersByIds($userIds);
    }

    public function syncEnrollmentParticipants(CourseEnrollment $enrollment, array $extraUserIds = []): void
    {
        $enrollment->loadMissing('course:id,teacher_id');

        $userIds = collect([
            $enrollment->student_id,
            $enrollment->course?->teacher_id,
        ])->merge($extraUserIds);

        $this->syncUsersByIds($userIds);
    }
}
