<?php

namespace App\Livewire\Forms;

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

class WorkTypeForm extends Form
{
    public ?int $project_id = null;

    public string $name = '';

    public bool $status = true;

    /** @return array<string, mixed> */
    public function rules(?int $ignoreWorkTypeId = null): array
    {
        return [
            'project_id' => ['required', 'integer', 'exists:projects,id'],
            'name' => [
                'required',
                'string',
                'min:2',
                'max:100',
                Rule::unique('work_types', 'name')
                    ->where(fn ($q) => $q->where('project_id', $this->project_id))
                    ->ignore($ignoreWorkTypeId),
            ],
            'status' => ['boolean'],
        ];
    }

    /** @return array<string, string> */
    public function validationMessages(): array
    {
        return [
            'project_id.required' => 'Seleccione el proyecto.',
            'project_id.exists' => 'El proyecto no es válido.',
            'name.required' => 'El nombre del tipo de trabajo es obligatorio.',
            'name.min' => 'El nombre debe tener al menos :min caracteres.',
            'name.max' => 'El nombre no puede superar :max caracteres.',
            'name.unique' => 'Ya existe un tipo de trabajo con este nombre en ese proyecto.',
        ];
    }

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

    public function fillFromModel(WorkType $workType): void
    {
        $this->project_id = (int) $workType->project_id;
        $this->name = $workType->name;
        $this->status = (bool) $workType->status;
    }
}
