<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

/**
 * Columnas del kanban de leads. Catálogo editable desde Ajustes, no
 * vocabulario fijo: `leads.status` guarda la `key` de una de estas filas.
 *
 * `is_converted` marca la etapa terminal y es exclusiva. Nunca comparar
 * contra la key literal en el código: usar la bandera.
 *
 * OJO: la tabla no tiene columna `id`; la clave primaria es `key` (text).
 */
class LeadStage extends Model
{
    protected $table = 'lead_stages';

    protected $primaryKey = 'key';

    protected $keyType = 'string';

    public $incrementing = false;

    protected $guarded = [];

    /** La tabla solo tiene created_at. */
    const UPDATED_AT = null;

    /**
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'position' => 'integer',
            'is_active' => 'boolean',
            'is_converted' => 'boolean',
            'created_at' => 'datetime',
        ];
    }

    /**
     * `is_converted` es exclusiva: al marcar una etapa se desmarcan las
     * demás. Se aplica aquí para que valga igual desde Filament que desde
     * cualquier otro punto del código, no solo desde el formulario.
     */
    protected static function booted(): void
    {
        static::saved(function (self $stage): void {
            if (! $stage->is_converted) {
                return;
            }

            static::query()
                ->whereKeyNot($stage->getKey())
                ->where('is_converted', true)
                ->update(['is_converted' => false]);
        });
    }

    public function leads(): HasMany
    {
        return $this->hasMany(Lead::class, 'status', 'key');
    }

    /**
     * Opciones key => name para los Select de Filament.
     *
     * @return array<string, string>
     */
    public static function options(): array
    {
        return static::query()
            ->where('is_active', true)
            ->orderBy('position')
            ->pluck('name', 'key')
            ->all();
    }
}
