<?php

namespace Tests\Feature;

use App\Models\Intent;
use App\Models\IntentPhrase;
use App\Models\Organization;
use App\Models\ResponseTemplate;
use App\Services\Bot\MatchIncomingMessage;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class BotMatchingServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_it_returns_an_approved_response_for_a_matching_intent_phrase(): void
    {
        $organization = Organization::factory()->create();
        $intent = Intent::factory()->create([
            'organization_id' => $organization->id,
            'name' => 'Delivery Charge',
            'slug' => 'delivery-charge',
            'confidence_threshold' => 0.7000,
        ]);

        IntentPhrase::factory()->create([
            'organization_id' => $organization->id,
            'intent_id' => $intent->id,
            'locale' => 'bn',
            'phrase' => 'delivery charge koto',
        ]);

        ResponseTemplate::factory()->create([
            'organization_id' => $organization->id,
            'intent_id' => $intent->id,
            'locale' => 'bn',
            'body' => 'Dhakar vitore delivery charge 80 taka.',
            'priority' => 10,
        ]);

        $match = app(MatchIncomingMessage::class)->handle(
            $organization,
            'Apnader delivery charge koto?',
            'bn',
        );

        $this->assertNotNull($match);
        $this->assertTrue($intent->is($match->intent));
        $this->assertSame('Dhakar vitore delivery charge 80 taka.', $match->responseTemplate->body);
        $this->assertGreaterThanOrEqual(0.7000, $match->confidence);
    }

    public function test_it_ignores_inactive_intents_and_unapproved_responses(): void
    {
        $organization = Organization::factory()->create();
        $intent = Intent::factory()->create([
            'organization_id' => $organization->id,
            'status' => 'inactive',
        ]);

        IntentPhrase::factory()->create([
            'organization_id' => $organization->id,
            'intent_id' => $intent->id,
            'phrase' => 'return policy',
        ]);

        ResponseTemplate::factory()->create([
            'organization_id' => $organization->id,
            'intent_id' => $intent->id,
            'status' => 'draft',
            'body' => 'Draft response.',
        ]);

        $match = app(MatchIncomingMessage::class)->handle($organization, 'return policy');

        $this->assertNull($match);
    }
}
