<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Relations\BelongsTo;

class TemplateItem extends BaseModel
{
    public function template(): BelongsTo
    {
        return $this->belongsTo(Template::class, 'template_uuid', 'uuid');
    }

    /**
     * Get all registers belonging to this item.
     * Assumes 'registers' column is a JSON array of UUIDs.
     */
    public function getRegisters()
    {
        $json = $this->registers;   // cast to array if you add $casts
        if (empty($json)) {
            return collect();
        }

        // Ensure it's an array (in case $casts is missing)
        $uuids = is_string($json) ? json_decode($json, true) : $json;
        if (!is_array($uuids) || empty($uuids)) {
            return collect();
        }

        return Register::whereIn('uuid', $uuids)->get();
    }

    /**
     * Get the device of the first register (kept as original).
     */
    public function getDevice()
    {
        return $this->getRegisters()->first()?->device;  // safer: use optional()
    }
}