<?php

namespace Tests\Feature;

use App\Console\Commands\SyncAutoTraderTaxonomies;
use App\Mail\NewVehicleMakesModelsMail;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use App\Master\Models\VehicleMake;
use App\Master\Models\VehicleModel;
use Tests\TenantTestCase;
use Tests\TestCase;

class AutoTraderVehicleSyncTest extends TenantTestCase
{
    /**
     * A basic feature test example.
     *
     * @return void
     */
    public function testTriggerSyncProcess()
    {
        $prefix = 'https://api-sandbox.autotrader.co.uk/taxonomy';
        Mail::fake();
        Http::fake([
            $prefix . '/makes*' => $this->makeResponse(),
            $prefix . '/models*' => $this->modelResponse(),
            '*' => Http::response(null, 400),
        ]);

        $command = $this->artisan(SyncAutoTraderTaxonomies::class);
        $command->run();
        $command->assertExitCode(0);

        $this->assertTrue(VehicleMake::query()->where('name', 'Fiat')->exists());
        $this->assertTrue(VehicleMake::query()->where('name', 'Ford')->exists());
        $this->assertTrue(VehicleModel::query()->where('name', 'Fiesta')->exists());
        $this->assertTrue(VehicleModel::query()->where('name', 'Mondeo')->exists());

        Http::assertSent(function (Request $request) {
            return Str::contains($request->url(), 'makes');
        });

        Http::assertSent(function (Request $request) {
            return Str::contains($request->url(), 'models');
        });

        Mail::assertQueued(NewVehicleMakesModelsMail::class);
    }

    private function makeResponse()
    {
        return Http::response([
            "makes" => [
                [
                    "makeId" => "2c9299d1712af419017130a7163969f4",
                    "name" => "Fiat"
                ],
                [
                    "makeId" => "2c9299017130a7163969f4d1712af419",
                    "name" => "Ford"
                ],
            ]
        ]);
    }

    private function modelResponse()
    {
        return Http::response([
            "models" => [
                [
                    "modelId" => "2c9299d1712af419017130a7163969f4",
                    "name" => "Fiesta"
                ],
                [
                    "modelId" => "2c9299017130a7163969f4d1712af419",
                    "name" => "Mondeo"
                ],
            ]

        ]);
    }
}
