<?php

namespace Tests\Tenant\Controllers;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Storage;
use Mtc\ContentManager\Models\Media;
use Mtc\ContentManager\Models\MediaUse;
use Mtc\MercuryDataModels\Vehicle;
use Tests\TenantTestCase;
use Carbon\Carbon;

class AutoImagingNotificationControllerTest extends TenantTestCase
{
    use WithFaker;

    /**
     * A basic feature test example.
     *
     * @return void
     */
    public function testListVehicles()
    {
        Config::set('services.image-sync.auto-imaging.key', 'abc');
        $params = [
            'tenant' => tenant('id'),
            'key' => 'abc'
        ];
        $vehicles = Vehicle::factory(3)->create([
            'stock_arrival_date' => Carbon::now()->subDays(10),
            'is_reserved' => false,
        ]);

        $response = $this->getJson(route('tenant.notifications.auto-imaging.index', $params));
        $response->assertStatus(200);
        $this->assertCount(3, $response->json('data'));
        $this->assertArrayHasKey('vrm', $response->json('data.0'));
        $this->assertArrayHasKey('vin', $response->json('data.0'));
        $this->assertArrayHasKey('make', $response->json('data.0'));
        $this->assertArrayHasKey('model', $response->json('data.0'));
        $this->assertArrayHasKey('cap_id', $response->json('data.0'));
        $this->assertArrayHasKey('odometer', $response->json('data.0'));
        $this->assertArrayHasKey('url', $response->json('data.0'));
    }

    public function testUpdateVehicle()
    {
        Storage::fake('media');
        Config::set('services.image-sync.auto-imaging.key', 'abc');
        $vehicle = Vehicle::factory()->create();
        if (empty($this->faker->image)) {
            $this->markTestSkipped('Unable to generate test image');
        }
        $response = $this->postJson(route('tenant.notifications.auto-imaging.index', tenant('id')), [
            'key' => 'abc',
            'vehicleId' => $vehicle->registration_number,
            'vimeoUrl' => 'http://foo.baz/bar',
            'images' => [
                ['large' => $this->faker->image],
            ]
        ]);

        $response->assertStatus(200);
        $vehicle->refresh();
        $this->assertEquals('http://foo.baz/bar', $vehicle->exterior_video_url);
        $this->assertEquals(1, $vehicle->mediaUses()->count());
    }

    public function testVehicleMissing()
    {
        Config::set('services.image-sync.auto-imaging.key', 'abc');
        $response = $this->postJson(route('tenant.notifications.auto-imaging.store', tenant('id')), [
            'key' => 'abc',
            'vehicleId' => 1
        ]);

        // 422 disabled to allow logging and deferred processing
        $response->assertStatus(200);
//        $this->assertArrayHasKey('vehicleId', $response->json('errors'));
    }
}
