<?php

namespace Tests\Unit\Services\Ranking;

use App\Services\Ranking\CatalogProductRankingExplainer;
use Tests\TestCase;

class CatalogProductRankingExplainerTest extends TestCase
{
    public function test_it_adds_comparative_ranking_reason_and_structured_signals(): void
    {
        config(['google-ads.ranking_use_keywords' => true]);

        $explained = (new CatalogProductRankingExplainer)->explain([
            [
                'name' => 'High demand chair',
                'url' => 'https://shop.example.com/chair-1',
                'rank' => 1,
                'rating' => '4.6',
                'review_count' => '320',
                'keyword_search_volume' => 50000,
                'keyword_competition' => 'HIGH',
                'matched_keyword' => 'office chair',
                'ranking_source' => 'heuristic',
            ],
            [
                'name' => 'Low demand chair',
                'url' => 'https://shop.example.com/chair-2',
                'rank' => 2,
                'rating' => '4.1',
                'review_count' => '12',
                'keyword_search_volume' => 1000,
                'keyword_competition' => 'HIGH',
                'matched_keyword' => 'task chair',
                'ranking_source' => 'heuristic',
            ],
        ]);

        $this->assertSame('keyword_search_volume', $explained[0]['ranking_signals']['primary_factor']);
        $this->assertStringContainsString('Ranked #1 above Low demand chair (#2)', $explained[0]['ranking_reason']);
        $this->assertStringContainsString('50,000 vs 1,000 monthly searches', $explained[0]['ranking_reason']);
        $this->assertStringContainsString('Included at rank #2', $explained[1]['ranking_reason']);
    }

    public function test_it_includes_ai_selection_note_in_ranking_reason(): void
    {
        $explained = (new CatalogProductRankingExplainer)->explain([
            [
                'name' => 'Top pick',
                'url' => 'https://shop.example.com/p/1',
                'rank' => 1,
                'review_count' => '100',
                'rating' => '4.8',
                'selection_reason' => 'Best mainstream appeal for the category',
                'ranking_source' => 'ai',
            ],
            [
                'name' => 'Runner up',
                'url' => 'https://shop.example.com/p/2',
                'rank' => 2,
                'review_count' => '80',
                'rating' => '4.5',
                'ranking_source' => 'ai',
            ],
        ]);

        $this->assertStringContainsString('AI selection note: Best mainstream appeal for the category', $explained[0]['ranking_reason']);
    }
}
