<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Relations\HasMany;

class Template extends BaseModel
{
    /**
     * If the template itself also stores register UUIDs directly
     * (similar to Form), keep this cast. Otherwise remove it.
     */
    protected $casts = [
        'registers' => 'array'
    ];

    public function items(): HasMany
    {
        return $this->hasMany(TemplateItem::class, 'template_uuid', 'uuid');
    }

    public function getTotal(): float|int
    {
        return $this->columns * $this->rows;
    }

    /**
     * Return an Eloquent query for all registers belonging to this template.
     * Aggregates UUIDs from all related template_items (and optionally the template itself).
     */
    public function registerQuery()
    {
        // 1. Collect UUIDs from template items
        $itemUuids = $this->items()
            ->get()
            ->pluck('registers')   // each is a JSON array like ["uuid1","uuid2"]
            ->filter()             // remove nulls
            ->map(fn($json) => json_decode($json, true))
            ->filter()             // remove invalid JSON
            ->flatten()
            ->unique()
            ->values()
            ->toArray();

        // 2. If the template itself has a 'registers' column, merge them
        $ownUuids = $this->registers ?? [];   // thanks to cast, it's an array

        // 3. Combine
        $allUuids = array_unique(array_merge($itemUuids, $ownUuids));

        if (empty($allUuids)) {
            return Register::query()->whereRaw('1 = 0');
        }

        return Register::whereIn('uuid', $allUuids);
    }
}