<?php

namespace ZenoChatbot\Model;

use ZenoChatbot\Framework\Database\QueryBuilder;

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

/**
 * Conversation sentiment meta (LLM-generated sentiment analysis).
 *
 * One row per conversation in zenochatbot_meta (meta_key = 'conversation_sentiment').
 * meta_value is a serialized array: label, reason, generated_at.
 */
class ConversationSentiment extends Meta
{
    public const META_KEY = 'conversation_sentiment';

    /**
     * Scope all queries to conversation sentiment 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 label from meta_value.
     *
     * @return string|null
     */
    public function getLabelAttribute(): ?string
    {
        $data = $this->getDecodedValue();
        $v = $data['label'] ?? null;
        return $v !== null && $v !== '' ? (string) $v : null;
    }

    /**
     * Get reason from meta_value.
     *
     * @return string|null
     */
    public function getReasonAttribute(): ?string
    {
        $data = $this->getDecodedValue();
        $v = $data['reason'] ?? null;
        return $v !== null && $v !== '' ? (string) $v : null;
    }

    /**
     * Get generated_at from meta_value.
     *
     * @return string|null
     */
    public function getGeneratedAtAttribute(): ?string
    {
        $data = $this->getDecodedValue();
        $v = $data['generated_at'] ?? null;
        return $v !== null && $v !== '' ? (string) $v : null;
    }

    /**
     * Decode meta_value to array.
     *
     * @return array<string,mixed>
     */
    protected function getDecodedValue(): array
    {
        if (!isset($this->attributes['meta_value']) && !isset($this->original['meta_value'])) {
            return [];
        }
        $raw = $this->attributes['meta_value'] ?? $this->original['meta_value'] ?? null;
        if ($raw === null) {
            return [];
        }
        $decoded = maybe_unserialize($raw);
        return is_array($decoded) ? $decoded : [];
    }
}
