<?php

namespace App\Http\Requests\Api\Auth;

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

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

    public function rules(): array
    {
        return [
            'nis' => 'required|string|exists:mai2.tsiswa,nis',
            'nouid' => 'nullable|string',
            'reset_token' => 'required|string|min:32',
            'pin' => 'required|digits:6|numeric|confirmed',
            'pin_confirmation' => 'required|digits:6',
            'device_name' => 'required|string|max:100',
        ];
    }

    public function messages(): array
    {
        return [
            'nis.exists' => 'NIS tidak valid.',
            'pin.digits' => 'PIN 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,
            ]);
        }
    }
}
