<?php
namespace boru\ai\Tests\Integration;

use boru\ai\AI;
use boru\ai\Conversation\ConversationReference;
use boru\ai\Persistence\Db\DbPersistenceProvider;

class DbConversationMemoryIntegrationTest extends DbIntegrationTestCase
{
    public function testConversationMemoryPersistsTitleSummaryAndNotes()
    {
        $this->bootstrapWithDbPersistence(null, null);

        $ai = AI::provider('openai')
            ->model('gpt-5.1')
            ->reference('memory-ref', 'user-memory');

        $ai->updateConversationTitle('Billing support');
        $ai->updateConversationSummary('Customer asked about a duplicate billing charge.');
        $ai->addConversationNote('Prefers email updates', 'preference', null, array('source' => 'agent'));
        $ai->addConversationNote('Needs invoice copy', 'task', null, array('priority' => 'high'));

        $this->assertSame(1, $this->countRows($this->tableNames['conversations']));
        $this->assertSame(2, $this->countRows($this->tableNames['conversation_notes']));

        $conversationRow = $this->fetchOne('select * from `' . $this->tableNames['conversations'] . '` order by `id` asc limit 1');
        $this->assertSame('Billing support', $conversationRow->get('title'));
        $this->assertStringContainsString('duplicate billing charge', $conversationRow->get('summary'));
        $this->assertSame('openai', $conversationRow->get('provider'));
        $this->assertSame('gpt-5.1', $conversationRow->get('model'));

        $firstNoteRow = $this->fetchOne('select * from `' . $this->tableNames['conversation_notes'] . '` order by `id` asc limit 1');
        $this->assertSame('preference', $firstNoteRow->get('kind'));
        $this->assertSame('Prefers email updates', $firstNoteRow->get('content'));
        $this->assertStringContainsString('agent', $firstNoteRow->get('metadata'));

        $persistence = AI::persistence();
        $this->assertInstanceOf(DbPersistenceProvider::class, $persistence);

        $reference = new ConversationReference();
        $reference->externalReference('memory-ref');
        $reference->userId('user-memory');
        $conversation = $persistence->loadConversation($reference);

        $this->assertSame('Billing support', $conversation->memory()->title());
        $this->assertSame('Customer asked about a duplicate billing charge.', $conversation->memory()->summary());
        $this->assertCount(2, $conversation->memory()->notes());
        $this->assertSame('preference', $conversation->memory()->notes()[0]->kind());
        $this->assertSame('Prefers email updates', $conversation->memory()->notes()[0]->text());
        $this->assertSame('agent', $conversation->memory()->notes()[0]->metadata('source'));
        $this->assertSame('task', $conversation->memory()->notes()[1]->kind());
    }
}
