<?php

namespace App\Rules;

use App\Models\SearchEvaluation;
use Closure;
use Illuminate\Contracts\Validation\DataAwareRule;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Translation\PotentiallyTranslatedString;

class ReuseStrategyRule implements DataAwareRule, ValidationRule
{
    /**
     * All the data under validation.
     *
     * @var array<string, mixed>
     */
    protected array $data = [];

    /**
     * Run the validation rule.
     *
     * @param Closure(string): PotentiallyTranslatedString $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        $evaluation = SearchEvaluation::find($this->data['evaluation'][SearchEvaluation::FIELD_ID] ?? null);

        if ($evaluation instanceof SearchEvaluation && $evaluation->hasStarted() && $value !== $evaluation->getReuseStrategy()) {
            $fail('Evaluation re-use strategy cannot be changed after it has started.');
        }
    }

    /**
     * Set the data under validation.
     *
     * @param  array<string, mixed>  $data
     */
    public function setData(array $data): static
    {
        $this->data = $data;

        return $this;
    }
}
