<?php

namespace Modules\Configuration\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Database\Factories\GradingRuleFactory;

class GradingRule extends Model
{
    use HasFactory;

    protected $fillable = [
        'academic_year_id',
        'grade',
        'min_marks',
        'max_marks',
        'points',
    ];

    protected function casts(): array
    {
        return [
            'min_marks' => 'integer',
            'max_marks' => 'integer',
            'points' => 'integer',
        ];
    }

    /**
     * Create a new factory instance for the model.
     */
    protected static function newFactory()
    {
        return GradingRuleFactory::new();
    }

    /**
     * Get the academic year this grading rule belongs to
     */
    public function academicYear(): BelongsTo
    {
        return $this->belongsTo(\Modules\Academic\Models\AcademicYear::class);
    }

    /**
     * Scope to get grading rules for a specific academic year
     */
    public function scopeForAcademicYear($query, $academicYearId)
    {
        return $query->where('academic_year_id', $academicYearId);
    }

    /**
     * Get the grade for given marks in a specific academic year
     */
    public static function getGradeForMarks(int $marks, int $academicYearId): ?string
    {
        $rule = static::forAcademicYear($academicYearId)
            ->where('min_marks', '<=', $marks)
            ->where('max_marks', '>=', $marks)
            ->first();

        return $rule?->grade;
    }

    /**
     * Get the points for given marks in a specific academic year
     */
    public static function getPointsForMarks(int $marks, int $academicYearId): ?int
    {
        $rule = static::forAcademicYear($academicYearId)
            ->where('min_marks', '<=', $marks)
            ->where('max_marks', '>=', $marks)
            ->first();

        return $rule?->points;
    }

    /**
     * Get all grading rules for an academic year ordered by min_marks desc
     */
    public static function getRulesForAcademicYear(int $academicYearId)
    {
        return static::forAcademicYear($academicYearId)
            ->orderBy('min_marks', 'desc')
            ->get();
    }
}
