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

use boru\ai\AI;
use boru\ai\Conversation\Conversation;
use boru\ai\Conversation\ConversationReference;
use boru\ai\Runtime\RuntimeContext;
use boru\ai\Tests\Fakes\FakePersistenceProvider;
use PHPUnit\Framework\TestCase;

class AIConversationMemoryFacadeTest extends TestCase
{
    /** @var FakePersistenceProvider */
    protected $persistence;

    protected function setUp(): void
    {
        AI::runtimeContext(new RuntimeContext());
        $this->persistence = new FakePersistenceProvider();
        AI::persistence($this->persistence);
    }

    public function testUpdateConversationTitleCreatesConversationWhenMissing()
    {
        $memory = AI::provider('openai')
            ->model('gpt-5.1')
            ->reference('chat-memory', 'user-1')
            ->updateConversationTitle('Support thread');

        $this->assertSame('Support thread', $memory->title());
        $this->assertCount(1, $this->persistence->savedConversations);
        $saved = $this->persistence->savedConversations[0];
        $this->assertSame('chat-memory', $saved->reference()->externalReference());
        $this->assertSame('user-1', $saved->reference()->userId());
        $this->assertSame('Support thread', $saved->memory()->title());
        $this->assertSame('openai', $saved->provider());
        $this->assertSame('gpt-5.1', $saved->model());
    }

    public function testAddConversationNoteAppendsToExistingConversationMemory()
    {
        $reference = new ConversationReference();
        $reference->externalReference('chat-memory');
        $reference->userId('user-1');

        $conversation = new Conversation($reference);
        $conversation->memory()->title('Existing title');
        $this->persistence->loadedConversation = $conversation;

        $note = AI::provider('openai')
            ->reference('chat-memory', 'user-1')
            ->addConversationNote('Customer prefers email follow-up', 'preference', null, array('source' => 'agent'));

        $this->assertSame('preference', $note->kind());
        $this->assertSame('Customer prefers email follow-up', $note->text());
        $this->assertCount(1, $this->persistence->savedConversations);
        $saved = $this->persistence->savedConversations[0];
        $this->assertSame('Existing title', $saved->memory()->title());
        $this->assertCount(1, $saved->memory()->notes());
        $this->assertSame('agent', $saved->memory()->notes()[0]->metadata('source'));
    }
}
