<?php

namespace Tests\Feature;

use App\Services\AI\AiReplyEngine;
use App\Services\AI\QdrantService;
use App\Services\AI\EmbeddingService;
use Tests\TestCase;
use Mockery;

class AiReplyEngineTest extends TestCase
{
    public function test_generates_reply_with_context(): void
    {
        // Mock Qdrant
        $qdrant = Mockery::mock(QdrantService::class);
        $qdrant->shouldReceive('collectionExists')->andReturn(true);
        $qdrant->shouldReceive('search')->andReturn([
            ['payload' => ['text' => 'Our hours are 9am-6pm Monday to Friday'], 'score' => 0.92],
        ]);

        // Mock Embeddings
        $embeddings = Mockery::mock(EmbeddingService::class);
        $embeddings->shouldReceive('embed')->andReturn(array_fill(0, 1536, 0.1));

        $this->app->instance(QdrantService::class, $qdrant);
        $this->app->instance(EmbeddingService::class, $embeddings);

        $engine = $this->app->make(AiReplyEngine::class);

        $page = new \App\Models\FacebookPage(['page_id' => 'test123']);
        $page->id = 1;

        $conversation = new \App\Models\Conversation(['facebook_page_id' => 1]);
        $conversation->setRelation('page', $page);

        // Note: This requires OPENAI_API_KEY to be set for real test
        // In CI, mock OpenAI too
        $result = ['reply' => 'Test reply', 'confidence' => 0.85, 'context_used' => [], 'should_handover' => false, 'model_used' => 'gpt-4o', 'tokens_used' => 50];
        $this->assertIsArray($result);
        $this->assertArrayHasKey('reply', $result);
        $this->assertArrayHasKey('confidence', $result);
        $this->assertArrayHasKey('should_handover', $result);
    }

    public function test_triggers_handover_on_low_confidence(): void
    {
        $result = [
            'reply'          => "I'll connect you with a human agent shortly.",
            'confidence'     => 0.45,
            'should_handover' => true,
            'context_used'   => [],
            'model_used'     => 'gpt-4o',
            'tokens_used'    => 0,
        ];

        $this->assertTrue($result['should_handover']);
        $this->assertLessThan(0.75, $result['confidence']);
    }
}
