<?php

namespace Tests\Tenant;

use App\Services\CarAndDrivingService;
use App\Facades\Settings;
use Database\Seeders\Tenant\CarAndDrivingReviewSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Artisan;
use Mtc\MercuryDataModels\Vehicle;
use Database\Seeders\Tenant\CarAndDrivingSeeder;
use Tests\TestCase;
use Tests\UserForTenant;

class CarAndDrivingImportTest extends TestCase
{
    use RefreshDatabase;
    use UserForTenant;

    protected $tenancy = true;

    protected function setUp(): void
    {
        parent::setUp();
 
        $this->seed(CarAndDrivingSeeder::class);
        $this->seed(CarAndDrivingReviewSeeder::class);

        Settings::shouldReceive('get')->andReturn(null)->byDefault();

        Http::preventStrayRequests();
    }

    public function testCreateReviewsAndVideo()
    { 
         Settings::shouldReceive('get')
            ->with('app-content-car-and-driving-enabled')
            ->once()
            ->andReturn(true);

        Settings::shouldReceive('get')
            ->with('app-content-car-and-driving-user-id')
            ->once()
            ->andReturn('test-tenant');

        Settings::shouldReceive('get')
            ->with('app-content-car-and-driving-should-sync-images')
            ->andReturn(true);

        Settings::shouldReceive('get')
            ->with('app-content-car-and-driving-should-sync-videos')
            ->andReturn(true);

        Settings::shouldReceive('get')
            ->with('app-content-car-and-driving-sync-type')
            ->once()
            ->andReturn('new');

        $this->mockApiResponse(); 

        Vehicle::factory()->create(['cap_id' => '102373']);

        Artisan::call('car-and-driving:bulk-import');

        $vehicle = Vehicle::factory()->create([
            'cap_id' => '102373',
        ]);

        $this->assertDatabaseHas('vehicle_reviews', [
            'external_review_id' => '12767'
        ]);

        $this->assertDatabaseHas('vehicles', [
            'cap_id' => '102373',
        ]);

        $vehicle = Vehicle::where('cap_id', '102373')->first();
        $this->assertEquals('https://ssl.caranddriving.com/f6/videos/shorts700/short_Abarth500e_2023.mp4', $vehicle->main_video_url);
    }

    public function testImportSkipsWhenIntegrationIsNotEnabled()
    {
        $this->mockApiResponse(); 

        Settings::shouldReceive('get')
            ->with('app-content-car-and-driving-enabled')
            ->once()
            ->andReturn(false);

        Artisan::call('car-and-driving:bulk-import');

        $this->assertDatabaseCount('vehicle_reviews', 0);
    }


    private function mockApiResponse()
    {
        $service = new CarAndDrivingService;
        Http::fake([ 
            $service->getEndpoint() . '*' => Http::response(
                file_get_contents(base_path('tests/data/car-and-driving.xml'), true),
                200
            ),
        ]);
    }
}