<?php

namespace App\Http\Controllers\Concerns;

use App\Models\SchoolClass;
use Illuminate\Http\Exceptions\HttpResponseException;

trait AuthorizesTeacherClass
{
    protected function teacherStaffId(): ?int
    {
        return auth()->user()?->staff_id;
    }

    protected function isTeacherOnly(): bool
    {
        $user = auth()->user();

        return $user !== null
            && $user->hasRole('Teacher')
            && ! $user->hasAnyRole(['Super Admin', 'Administrator', 'Registrar']);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Builder<SchoolClass>
     */
    protected function assignedClassesQuery()
    {
        $query = SchoolClass::query()->orderBy('name');
        $staffId = $this->teacherStaffId();

        if ($this->isTeacherOnly() && $staffId) {
            $query->where('class_teacher_id', $staffId);
        }

        return $query;
    }

    protected function authorizeClassAccess(int $classId): SchoolClass
    {
        $schoolClass = SchoolClass::query()->findOrFail($classId);

        if ($this->isTeacherOnly()) {
            $staffId = $this->teacherStaffId();

            if (! $staffId || (int) $schoolClass->class_teacher_id !== $staffId) {
                abort(403, 'You are not assigned to this class.');
            }
        }

        return $schoolClass;
    }
}
