<?php

namespace App\Http\Requests\Api\Auth;

use App\Models\Datmas\Siswa;
use Illuminate\Foundation\Http\FormRequest;

class VerifyResetOtpRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'nis' => 'required|string|exists:mai2.tsiswa,nis',
            'nouid' => 'nullable|string',
            'phone' => 'required|string|regex:/^[0-9]+$/|min:10|max:15',
            'otp' => 'required|string|digits:6',
        ];
    }

    public function messages(): array
    {
        return [
            'nis.exists' => 'NIS tidak valid.',
            'otp.digits' => 'OTP harus terdiri dari 6 digit angka.',
        ];
    }

    protected function prepareForValidation(): void
    {
        if (!$this->filled('nis') || $this->filled('nouid')) {
            return;
        }

        $siswa = Siswa::query()
            ->with('indentitas')
            ->where('nis', $this->string('nis')->toString())
            ->first();

        if ($siswa?->indentitas) {
            $this->merge([
                'nouid' => $siswa->indentitas->nouid,
            ]);
        }
    }
}
