<?php

namespace App\Rules;

use App\Enum\Assessment\QuestionTypeEnum;
use App\Models\Assessment\Question;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;

class AssessmentAnswerRule implements ValidationRule
{
    protected $column_type;
    protected $question_id;
    public function __construct($column_type, $question_id)
    {
        $this->column_type = $column_type;
        $this->question_id = $question_id;

    }
    /**
     * Run the validation rule.
     *
     * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        $question = Question::query()->find($this->question_id);

        if (!$question) {
            $fail("Question is invalid");
            return;
        }

        if ($this->column_type === 'answer') {
            if ($question->question_type === QuestionTypeEnum::OPEN_ENDED->value) {
                $fail("Answers are not required for this question type");
                return;
            }
        }

        if ($this->column_type === 'is_correct') {
            $correctAnswersCount = $question->answers()->where('is_correct', true)->count();
            if ($value && $correctAnswersCount >= 1) {
                $fail("Only ONE (1) correct answer is needed");
                return;
            }
        }


    }
}
