<?php

namespace App\Http\Requests\Api\Auth;

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

class ForgotPinRequest 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',
        ];
    }

    public function messages(): array
    {
        return [
            'nis.exists' => 'NIS tidak valid.',
            'phone.regex' => 'Nomor telepon hanya boleh berisi 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,
            ]);
        }
    }
}
