<?php
namespace boru\ai\Persistence\Db;

use boru\ai\Conversation\ConversationReference;

class DbConversationInspector
{
    /** @var DbConnection */
    protected $connection;

    public function __construct(DbConnection $connection = null)
    {
        $this->connection = $connection ? $connection : new DbConnection();
    }

    public function connection(DbConnection $connection = null)
    {
        if ($connection !== null) {
            $this->connection = $connection;
            return $this;
        }
        return $this->connection;
    }

    public function loadConversationRecord(ConversationReference $reference)
    {
        if (!$reference->id() && !$reference->externalReference()) {
            return false;
        }

        $db = $this->connection()->db();
        $sql = 'select * from `' . $this->table('conversations') . '`';
        $params = array();

        if ($reference->id()) {
            $sql .= ' where `conversation_id`=?';
            $params[] = $reference->id();
        } else {
            $sql .= ' where `external_reference`=?';
            $params[] = $reference->externalReference();
            if ($reference->userId()) {
                $sql .= ' and `user_id`=?';
                $params[] = $reference->userId();
            }
        }

        $sql .= ' limit 1';
        $result = $this->connection()->run($sql, $params);
        $row = $db->next($result);
        return $row ? $row->asArray() : false;
    }

    public function listTurnRecords($conversationPk)
    {
        $db = $this->connection()->db();
        $sql = 'select * from `' . $this->table('turns') . '` where `conversation_pk`=? order by `turn_number` asc';
        $result = $this->connection()->run($sql, array($conversationPk));

        $rows = array();
        while ($row = $db->next($result)) {
            $rows[] = $row->asArray();
        }
        return $rows;
    }

    public function listToolCallRecords($turnPk)
    {
        $db = $this->connection()->db();
        $sql = 'select * from `' . $this->table('tool_calls') . '` where `turn_pk`=? order by `sequence_number` asc';
        $result = $this->connection()->run($sql, array($turnPk));

        $rows = array();
        while ($row = $db->next($result)) {
            $rows[] = $row->asArray();
        }
        return $rows;
    }

    protected function table($key)
    {
        return $this->connection()->config()->table($key);
    }
}
