<?php

namespace Tests\Unit\Services\Ranking;

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

class HeuristicCatalogProductRankerTest extends TestCase
{
    public function test_it_sorts_by_reviews_and_ratings_and_limits_results(): void
    {
        config(['scraping.ranking.limit' => 2]);

        $ranked = (new HeuristicCatalogProductRanker)->rank([
            [
                'name' => 'Low signal',
                'url' => 'https://shop.example.com/p/1',
                'rating' => '3',
                'review_count' => '2',
            ],
            [
                'name' => 'Top pick',
                'url' => 'https://shop.example.com/p/2',
                'rating' => '4.8',
                'review_count' => '120',
            ],
            [
                'name' => 'Runner up',
                'url' => 'https://shop.example.com/p/3',
                'rating' => '4.5',
                'review_count' => '80',
            ],
        ]);

        $this->assertCount(2, $ranked);
        $this->assertSame('https://shop.example.com/p/2', $ranked[0]['url']);
        $this->assertSame(1, $ranked[0]['rank']);
        $this->assertSame('Best Overall', $ranked[0]['best_for']);
        $this->assertSame('https://shop.example.com/p/3', $ranked[1]['url']);
    }

    public function test_it_prioritizes_keyword_search_volume_when_keyword_ranking_is_enabled(): void
    {
        config([
            'scraping.ranking.limit' => 2,
            'google-ads.ranking_use_keywords' => true,
        ]);

        $ranked = (new HeuristicCatalogProductRanker)->rank([
            [
                'name' => 'Low demand',
                'url' => 'https://shop.example.com/p/1',
                'rating' => '4.9',
                'review_count' => '500',
                'keyword_search_volume' => 1000,
            ],
            [
                'name' => 'High demand',
                'url' => 'https://shop.example.com/p/2',
                'rating' => '4.0',
                'review_count' => '10',
                'keyword_search_volume' => 50000,
            ],
        ]);

        $this->assertSame('https://shop.example.com/p/2', $ranked[0]['url']);
        $this->assertStringContainsString('50,000 monthly searches', $ranked[0]['selection_reason']);
    }
}
