<?php

namespace Tests\Tenant;

use Mtc\MercuryDataModels\Vehicle;
use Tests\TenantTestCase;
use Tests\UserForTenant;

class VehicleOrderTest extends TenantTestCase
{
    use UserForTenant;

    public function testSaveOrderUpdatesCorrectly()
    {
        $vehicles = Vehicle::factory()
            ->count(3)
            ->sequence(
                ['order' => 1],
                ['order' => 2],
                ['order' => 3],
            )->create();

        $newOrder = [$vehicles[2]->id, $vehicles[0]->id, $vehicles[1]->id];
        $payload = collect($newOrder)->map(fn ($id) => ['id' => $id])->toArray();

        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->putJson(route('tenant.vehicles.save-order'), $payload);

        $response->assertOk();

        $this->assertDatabaseHas('vehicles', ['id' => $vehicles[2]->id, 'order' => 1]);
        $this->assertDatabaseHas('vehicles', ['id' => $vehicles[0]->id, 'order' => 2]);
        $this->assertDatabaseHas('vehicles', ['id' => $vehicles[1]->id, 'order' => 3]);
    }

    public function testSaveOrderHandlesNullOrderValues()
    {
        $vehicles = Vehicle::factory()
            ->count(3)
            ->sequence(
                ['order' => null],
                ['order' => null],
                ['order' => null],
            )->create();

        $newOrder = [$vehicles[2]->id, $vehicles[0]->id, $vehicles[1]->id];
        $payload = collect($newOrder)->map(fn ($id) => ['id' => $id])->toArray();

        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->putJson(route('tenant.vehicles.save-order'), $payload);

        $response->assertOk();

        $this->assertDatabaseHas('vehicles', ['id' => $vehicles[2]->id, 'order' => 0]);
        $this->assertDatabaseHas('vehicles', ['id' => $vehicles[0]->id, 'order' => 1]);
        $this->assertDatabaseHas('vehicles', ['id' => $vehicles[1]->id, 'order' => 2]);
    }

    public function testSetOrderValueAppendsToEnd()
    {
        Vehicle::factory()
            ->count(2)
            ->sequence(
                ['order' => 0],
                ['order' => 1],
            )->create();

        $vehicle = Vehicle::factory()->create(['order' => null]);

        $this->assertEquals(2, $vehicle->fresh()->order);
    }

    public function testSetOrderValueStartsAtZeroWhenNoVehiclesExist()
    {
        $vehicle = Vehicle::factory()->create(['order' => null]);

        $this->assertEquals(0, $vehicle->fresh()->order);
    }

}
