<?php

namespace App\Http\Controllers\Concerns;

use App\Models\Exam;
use App\Models\Lesson;
use App\Models\Question;
use Illuminate\Database\Eloquent\Builder;

trait RestrictsTeacherLessons
{
    protected function teacherLessonIds(): array
    {
        return auth()->user()->lessons()->pluck('lessons.id')->all();
    }

    protected function teacherLessons(): Builder
    {
        return Lesson::query()->whereIn('id', $this->teacherLessonIds());
    }

    protected function teacherQuestions(): Builder
    {
        return Question::query()->whereIn('lesson_id', $this->teacherLessonIds());
    }

    protected function teacherExams(): Builder
    {
        return Exam::query()->whereIn('lesson_id', $this->teacherLessonIds());
    }

    protected function findTeacherExamOrFail(int $id): Exam
    {
        return $this->teacherExams()->findOrFail($id);
    }

    protected function ensureTeacherOwnsLesson(int $lessonId): void
    {
        abort_unless(in_array($lessonId, $this->teacherLessonIds(), true), 403);
    }
}
