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

use boru\ai\AI;
use boru\ai\Bootstrap;
use boru\ai\Config\Config;
use boru\ai\Persistence\Db\DbAssetStore;
use boru\ai\Persistence\Db\DbPersistenceProvider;
use boru\ai\Persistence\Db\DbEmbeddingStore;
use boru\ai\Persistence\NullPersistenceProvider;
use boru\ai\Runtime\RuntimeContext;
use PHPUnit\Framework\TestCase;

class BootstrapPersistenceTest extends TestCase
{
    protected function setUp(): void
    {
        AI::runtimeContext(new RuntimeContext());
    }

    public function testRegisterDefaultsLeavesNullPersistenceWhenDisabled()
    {
        $config = new Config();
        $config->provider('openai', array('api_key' => 'test-key'));
        $config->persistence(array(
            'enabled' => false,
        ));

        Bootstrap::registerDefaults($config);

        $this->assertInstanceOf(NullPersistenceProvider::class, AI::persistence());
    }

    public function testRegisterDefaultsRegistersDbPersistenceWhenEnabled()
    {
        $config = new Config();
        $config->provider('openai', array('api_key' => 'test-key'));
        $config->persistence(array(
            'enabled' => true,
            'driver' => 'db',
        ));
        $config->db(array(
            'use' => false,
            'dbhost' => '127.0.0.1',
            'dbport' => 3306,
            'dbname' => 'ai_test',
            'dbuser' => 'root',
            'dbpass' => '',
            'dbtype' => 'mysql',
        ));

        Bootstrap::registerDefaults($config);

        $provider = AI::persistence();
        $this->assertInstanceOf(DbPersistenceProvider::class, $provider);
        /** @var DbPersistenceProvider $provider */
        $this->assertSame('ai_conversations', $provider->connection()->config()->table('conversations'));

        $assetStore = AI::assetStore();
        $this->assertInstanceOf(DbAssetStore::class, $assetStore);
        /** @var DbAssetStore $assetStore */
        $this->assertSame('ai_assets', $assetStore->connection()->config()->table('assets'));

        $embeddingStore = AI::embeddingStore();
        $this->assertInstanceOf(DbEmbeddingStore::class, $embeddingStore);
        /** @var DbEmbeddingStore $embeddingStore */
        $this->assertSame('ai_embeddings', $embeddingStore->connection()->config()->table('embeddings'));
        $this->assertSame('ai_conversation_notes', $provider->connection()->config()->table('conversation_notes'));
    }

    public function testEnsurePersistenceSchemaReturnsFalseWhenPersistenceDisabled()
    {
        $config = new Config();
        $config->persistence(array(
            'enabled' => false,
        ));

        $this->assertFalse(Bootstrap::ensurePersistenceSchema($config));
    }
}
