<?php

namespace Tests\Unit\Services\Keywords;

use App\Services\Keywords\AiKeywordCandidateMatcher;
use Laravel\Ai\StructuredAnonymousAgent;
use Tests\TestCase;

class AiKeywordCandidateMatcherTest extends TestCase
{
    public function test_it_matches_products_to_keywords_with_ai(): void
    {
        config(['google-ads.ai_keyword_matching' => true]);

        StructuredAnonymousAgent::fake([
            ['matches' => [
                [
                    'index' => 1,
                    'term' => 'office chair',
                    'match_reason' => 'This is a mesh office chair, not a desk or tent.',
                ],
                [
                    'index' => 2,
                    'term' => '',
                    'match_reason' => 'No keyword describes a desk well enough.',
                ],
            ]],
        ]);

        $matches = (new AiKeywordCandidateMatcher)->match(
            [
                ['name' => 'Ergonomic Mesh Office Chair', 'url' => 'https://shop.example.com/chair'],
                ['name' => 'Magellan L-Shape Desk', 'url' => 'https://shop.example.com/desk'],
            ],
            [
                [
                    'term' => 'office chair',
                    'avg_monthly_searches' => 201000,
                    'competition' => 'HIGH',
                ],
                [
                    'term' => 'camping tent',
                    'avg_monthly_searches' => 50000,
                    'competition' => 'MEDIUM',
                ],
            ],
            'Office',
            'Chairs',
        );

        $this->assertSame('office chair', $matches[0]['term']);
        $this->assertStringContainsString('mesh office chair', $matches[0]['match_reason']);
        $this->assertArrayNotHasKey(1, $matches);
    }

    public function test_it_returns_no_matches_when_ai_matching_is_disabled(): void
    {
        config(['google-ads.ai_keyword_matching' => false]);

        $matches = (new AiKeywordCandidateMatcher)->match(
            [['name' => 'Office Chair', 'url' => 'https://shop.example.com/chair']],
            [['term' => 'office chair', 'avg_monthly_searches' => 1000, 'competition' => 'HIGH']],
        );

        $this->assertSame([], $matches);
    }
}
