<?php

namespace Tests\Feature;

use App\Models\Category;
use App\Services\SkySportsService;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

class SportsRoutesTest extends TestCase
{
    use DatabaseMigrations;

    protected function setUp(): void
    {
        parent::setUp();
        
        // Seed test data
        $this->seedTestData();
    }

    /**
     * Seed test data for categories
     */
    protected function seedTestData()
    {
        Category::create([
            'name' => 'Football',
            'slug' => 'football',
            'description' => 'Football news and updates'
        ]);

        Category::create([
            'name' => 'Basketball',
            'slug' => 'basketball',
            'description' => 'Basketball news and updates'
        ]);

        Category::create([
            'name' => 'Tennis',
            'slug' => 'tennis',
            'description' => 'Tennis news and updates'
        ]);
    }

    /**
     * Test sports index page loads successfully
     */
    public function test_sports_index_page_loads_successfully()
    {
        $mockData = [
            [
                'poster' => 'https://via.placeholder.com/300x200?text=Sports+Image',
                'title' => 'Latest Sports News Update',
                'tag' => 'Football',
                'link' => '/football/news/12345/67890/latest-news',
                'sports' => 'football',
                'type' => 'news',
                'news' => 'latest-news',
                'idsport' => '12345',
                'id' => '67890',
                'more' => '0'
            ],
            'total_results' => 1
        ];

        // Mock the service
        $this->mock(SkySportsService::class)
            ->shouldReceive('getSportsCategories')
            ->once()
            ->with('sports', '29876', 1)
            ->andReturn($mockData);

        Cache::shouldReceive('remember')
            ->andReturnUsing(function ($key, $ttl, $callback) {
                return $callback();
            });

        $response = $this->get('/sports');

        $response->assertStatus(200);
        $response->assertViewIs('sports.index');
        $response->assertViewHas('sportsData', $mockData);
        $response->assertViewHas('categories');
        $response->assertSee('Latest Sports News Update');
        $response->assertSee('FOOTBALL'); // Category badge
    }

    /**
     * Test sports category page loads successfully
     */
    public function test_sports_category_page_loads_successfully()
    {
        $mockData = [
            [
                'poster' => 'https://via.placeholder.com/300x200?text=Basketball+Update',
                'title' => 'Basketball Championship Results',
                'tag' => 'Basketball',
                'link' => '/basketball/news/54321/09876/championship-results',
                'sports' => 'basketball',
                'type' => 'news',
                'news' => 'championship-results',
                'idsport' => '54321',
                'id' => '09876',
                'more' => '0'
            ],
            'total_results' => 1
        ];

        $this->mock(SkySportsService::class)
            ->shouldReceive('getSportsCategories')
            ->once()
            ->with('basketball', '11095', 1)
            ->andReturn($mockData);

        Cache::shouldReceive('remember')
            ->andReturnUsing(function ($key, $ttl, $callback) {
                return $callback();
            });

        $response = $this->get('/sports/basketball');

        $response->assertStatus(200);
        $response->assertViewIs('sports.index');
        $response->assertViewHas('sportsData', $mockData);
        $response->assertSee('Basketball Championship Results');
        $response->assertSee('BASKETBALL'); // Category badge
        $response->assertSee('Basketball'); // Page title
    }

    /**
     * Test sports search functionality
     */
    public function test_sports_search_functionality()
    {
        $mockData = [
            [
                'poster' => 'https://via.placeholder.com/300x200?text=Search+Result',
                'title' => 'Championship Final Results',
                'tag' => 'Football',
                'link' => '/football/news/999/888/championship-final',
                'sports' => 'football',
                'type' => 'news',
                'news' => 'championship-final',
                'idsport' => '999',
                'id' => '888',
                'more' => '0'
            ],
            [
                'poster' => 'https://via.placeholder.com/300x200?text=Other+Result',
                'title' => 'Other Match Results',
                'tag' => 'Football',
                'link' => '/football/news/777/666/other-match',
                'sports' => 'football',
                'type' => 'news',
                'news' => 'other-match',
                'idsport' => '777',
                'id' => '666',
                'more' => '0'
            ],
            'total_results' => 2
        ];

        $this->mock(SkySportsService::class)
            ->shouldReceive('getSportsCategories')
            ->once()
            ->with('search', '29876', 1)
            ->andReturn($mockData);

        Cache::shouldReceive('remember')
            ->andReturnUsing(function ($key, $ttl, $callback) {
                return $callback();
            });

        $response = $this->get('/sports/search?s=championship');

        $response->assertStatus(200);
        $response->assertViewIs('sports.search');
        $response->assertViewHas('query', 'championship');
        $response->assertViewHas('sportsData');
        
        // Should only show results containing 'championship'
        $viewData = $response->original->getData();
        $this->assertEquals(1, $viewData['sportsData']['total_results']);
        $response->assertSee('Championship Final Results');
        $response->assertDontSee('Other Match Results'); // Should be filtered out
    }

    /**
     * Test sports search redirects when query is empty
     */
    public function test_sports_search_redirects_when_query_empty()
    {
        $response = $this->get('/sports/search?s=');

        $response->assertStatus(302);
        $response->assertRedirect(route('home'));
    }

    /**
     * Test sports article page loads successfully
     */
    public function test_sports_article_page_loads_successfully()
    {
        $mockArticleData = [
            'title' => 'Premier League Match Preview',
            'date' => '2024-01-15 14:30',
            'images' => 'https://example.com/preview-image.jpg',
            'og-images' => 'https://example.com/og-preview.jpg',
            'article' => [
                'This is the first paragraph of the match preview.',
                'Both teams have been preparing extensively for this encounter.',
                'The match promises to be an exciting affair with lots of action.'
            ]
        ];

        $this->mock(SkySportsService::class)
            ->shouldReceive('getSportsArticle')
            ->once()
            ->with('football', 'news', '12345', '67890', 'match-preview', '')
            ->andReturn($mockArticleData);

        Cache::shouldReceive('remember')
            ->andReturnUsing(function ($key, $ttl, $callback) {
                return $callback();
            });

        $response = $this->get('/sports/football/news/12345/67890/match-preview');

        $response->assertStatus(200);
        $response->assertViewIs('sports.article');
        $response->assertViewHas('articleData', $mockArticleData);
        $response->assertViewHas('sport', 'football');
        $response->assertViewHas('type', 'news');
        $response->assertSee('Premier League Match Preview');
        $response->assertSee('2024-01-15 14:30');
        $response->assertSee('This is the first paragraph of the match preview.');
    }

    /**
     * Test sports article with more-sports parameter
     */
    public function test_sports_article_with_more_sports_parameter()
    {
        $mockArticleData = [
            'title' => 'Tennis Championship Finals',
            'date' => '2024-01-15 16:00',
            'images' => 'https://example.com/tennis-image.jpg',
            'og-images' => 'https://example.com/og-tennis.jpg',
            'article' => [
                'The tennis championship finals are set to begin.',
                'Both players have shown exceptional skill throughout the tournament.'
            ]
        ];

        $this->mock(SkySportsService::class)
            ->shouldReceive('getSportsArticle')
            ->once()
            ->with('tennis', 'news', '11111', '22222', 'championship-finals', 'more-sports')
            ->andReturn($mockArticleData);

        Cache::shouldReceive('remember')
            ->andReturnUsing(function ($key, $ttl, $callback) {
                return $callback();
            });

        $response = $this->get('/more-sports/tennis/news/11111/22222/championship-finals?more=more-sports');

        $response->assertStatus(200);
        $response->assertViewIs('sports.article');
        $response->assertViewHas('articleData', $mockArticleData);
        $response->assertSee('Tennis Championship Finals');
    }

    /**
     * Test sports article redirects when required parameters are missing
     */
    public function test_sports_article_redirects_when_parameters_missing()
    {
        $response = $this->get('/sports/football/news//67890/match-preview');

        $response->assertStatus(404); // Laravel will return 404 for missing route parameters
    }

    /**
     * Test sports pages handle API failures gracefully
     */
    public function test_sports_pages_handle_api_failures_gracefully()
    {
        // Mock API failure - service should return mock data instead of throwing exception
        $mockData = [
            [
                'poster' => 'https://via.placeholder.com/300x200?text=Fallback+Data',
                'title' => 'Latest Sports News Update',
                'tag' => 'Football',
                'link' => '/football/news/12345/67890/latest-news',
                'sports' => 'football',
                'type' => 'news',
                'news' => 'latest-news',
                'idsport' => '12345',
                'id' => '67890',
                'more' => '0'
            ],
            'total_results' => 1
        ];

        $this->mock(SkySportsService::class)
            ->shouldReceive('getSportsCategories')
            ->once()
            ->andReturn($mockData);

        Cache::shouldReceive('remember')
            ->andReturnUsing(function ($key, $ttl, $callback) {
                return $callback();
            });

        $response = $this->get('/sports');

        $response->assertStatus(200);
        $response->assertViewIs('sports.index');
        // Should show mock data when API fails
        $response->assertSee('Latest Sports News Update');
    }

    /**
     * Test pagination works correctly
     */
    public function test_pagination_works_correctly()
    {
        $mockData = [
            [
                'poster' => 'https://via.placeholder.com/300x200?text=Page2',
                'title' => 'Page 2 Sports News',
                'tag' => 'Football',
                'link' => '/football/news/222/333/page2',
                'sports' => 'football',
                'type' => 'news',
                'news' => 'page2',
                'idsport' => '222',
                'id' => '333',
                'more' => '0'
            ],
            'total_results' => 25 // More than one page
        ];

        $this->mock(SkySportsService::class)
            ->shouldReceive('getSportsCategories')
            ->once()
            ->with('sports', '29876', 2)
            ->andReturn($mockData);

        Cache::shouldReceive('remember')
            ->andReturnUsing(function ($key, $ttl, $callback) {
                return $callback();
            });

        $response = $this->get('/sports?page=2');

        $response->assertStatus(200);
        $response->assertViewHas('page', 2);
        $response->assertSee('Page 2 Sports News');
        // Should show pagination controls
        $response->assertSee('Previous');
    }

    /**
     * Test caching behavior
     */
    public function test_caching_behavior()
    {
        $mockData = [
            [
                'poster' => 'https://via.placeholder.com/300x200?text=Cached',
                'title' => 'Cached Sports News',
                'tag' => 'Football',
                'link' => '/football/news/999/888/cached',
                'sports' => 'football',
                'type' => 'news',
                'news' => 'cached',
                'idsport' => '999',
                'id' => '888',
                'more' => '0'
            ],
            'total_results' => 1
        ];

        // Mock the service to be called (caching will handle multiple calls)
        $this->mock(SkySportsService::class)
            ->shouldReceive('getSportsCategories')
            ->andReturn($mockData);

        // First request
        $response1 = $this->get('/sports');
        $response1->assertStatus(200);
        $response1->assertSee('Cached Sports News');

        // Second request should use cache (service should not be called again)
        $response2 = $this->get('/sports');
        $response2->assertStatus(200);
        $response2->assertSee('Cached Sports News');
    }
}
