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

use boru\ai\AI;
use boru\ai\Conversation\ConversationReference;
use boru\ai\Persistence\Db\DbPersistenceProvider;
use boru\ai\Tests\Fakes\FakeHttpClient;

class DbBootstrapChatPersistenceIntegrationTest extends DbIntegrationTestCase
{
    public function testBootstrapChatRunPersistsConversationAndTurnRows()
    {
        $httpClient = new FakeHttpClient();
        $httpClient->queueResponse($this->jsonResponse(array(
            'id' => 'resp_db_chat_1',
            'model' => 'gpt-5.1',
            'status' => 'completed',
            'output' => array(
                array(
                    'type' => 'message',
                    'content' => array(
                        array(
                            'type' => 'output_text',
                            'text' => 'Persisted hello',
                        ),
                    ),
                ),
            ),
            'usage' => array(
                'input_tokens' => 4,
                'output_tokens' => 2,
                'total_tokens' => 6,
            ),
        )));

        $this->bootstrapWithDbPersistence($httpClient, null);

        $response = AI::provider('openai')
            ->reference('db-chat-ref', 'user-1')
            ->model('gpt-5.1')
            ->addMessage('Persist this turn')
            ->run();

        $this->assertSame('Persisted hello', $response->text());
        $this->assertCount(1, $httpClient->requests);
        $this->assertSame(1, $this->countRows($this->tableNames['conversations']));
        $this->assertSame(1, $this->countRows($this->tableNames['turns']));

        $conversationRow = $this->fetchOne('select * from `' . $this->tableNames['conversations'] . '` where `external_reference`=? and `user_id`=? limit 1', array('db-chat-ref', 'user-1'));
        $this->assertSame('openai', $conversationRow->get('provider'));
        $this->assertSame('gpt-5.1', $conversationRow->get('model'));

        $turnRow = $this->fetchOne('select * from `' . $this->tableNames['turns'] . '` order by `id` asc limit 1');
        $this->assertSame('completed', $turnRow->get('status'));
        $this->assertStringContainsString('Persist this turn', $turnRow->get('request_json'));
        $this->assertStringContainsString('Persisted hello', $turnRow->get('response_json'));

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

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

        $this->assertSame('openai', $conversation->provider());
        $this->assertSame('gpt-5.1', $conversation->model());
        $this->assertCount(1, $conversation->turns());
        $this->assertSame('Persisted hello', $conversation->turns()[0]->response()->text());
    }
}
