<?php

namespace App\Trait;

use App\Models\Meta;
use Illuminate\Database\Eloquent\Relations\MorphMany;

trait HasMeta {
    /**
     * Set a meta value.
     */
    public function setMeta(string $key, $value): void {
        $this->metas()->updateOrCreate(
            ['key' => $key],
            ['value' => $value]
        );
    }

    /**
     * Define the relationship to the Meta model.
     * Assumes a 'metas' table with: id, owner_id, owner_type, key, value
     */
    public function metas(): MorphMany {
        return $this->morphMany(Meta::class, 'owner');
    }

    /**
     * Get a specific meta value.
     */
    public function getMeta(string $key, $default = null) {
        $meta = $this->metas()->where('key', $key)->first();
        return $meta ? $meta->value : $default;
    }

    /**
     * Delete a specific meta key.
     */
    public function deleteMeta(string $key): void {
        $this->metas()->where('key', $key)->delete();
    }

    /**
     * Retrieve all meta as a key-value array.
     */
    public function getAllMeta(): array {
        return $this->metas()->pluck('value', 'key')->toArray();
    }
}