<?php

namespace ZenoChatbot\Model;

use ZenoChatbot\Framework\Database\QueryBuilder;

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Conversation notes meta (agent-added notes on a conversation).
 *
 * One row per conversation in zenochatbot_meta (meta_key = 'conversation_notes').
 * meta_value is a serialized array of note objects.
 * Distinct from Knowledge Notes (LLM context).
 */
class ConversationNotes extends Meta
{
    public const META_KEY = 'conversation_notes';

    /**
     * Scope all queries to conversation notes rows (e.g. for eager load).
     *
     * @return QueryBuilder
     */
    public function newQuery()
    {
        return parent::newQuery()
            ->where('entity_type', Conversation::class)
            ->where('meta_key', self::META_KEY);
    }

    /**
     * Get the list of note items (unserialized from meta_value).
     *
     * @return array<int,array<string,mixed>>
     */
    public function getItems(): array
    {
        $raw = $this->attributes['meta_value'] ?? $this->original['meta_value'] ?? null;
        if ($raw === null) {
            return [];
        }
        $decoded = maybe_unserialize($raw);
        if (!is_array($decoded)) {
            return [];
        }
        return array_values($decoded);
    }
}
