<?php

namespace App\Livewire\Forms;

use App\Models\District;
use Illuminate\Validation\Rule;
use Livewire\Form;

class DistrictForm extends Form
{
    public string $name = '';

    public ?int $province_id = null;

    /** @return array<string, mixed> */
    public function rules(?int $ignoreDistrictId = null): array
    {
        return [
            'name' => [
                'required',
                'string',
                'min:2',
                'max:100',
                Rule::unique('districts', 'name')
                    ->where(fn ($query) => $query->where('province_id', $this->province_id))
                    ->ignore($ignoreDistrictId),
            ],
            'province_id' => ['required', 'integer', 'exists:provinces,id'],
        ];
    }

    /** @return array<string, string> */
    public function validationMessages(): array
    {
        return [
            'name.required' => 'El nombre del distrito es obligatorio.',
            'name.unique' => 'Este distrito ya existe en la provincia seleccionada.',
            'province_id.required' => 'Debes seleccionar una provincia.',
            'province_id.exists' => 'La provincia seleccionada no es válida.',
        ];
    }

    public function resetForCreate(): void
    {
        $this->name = '';
        $this->province_id = null;
    }

    public function fillFromModel(District $district): void
    {
        $this->name = $district->name;
        $this->province_id = $district->province_id;
    }
}
