<?php

namespace Tests\Tenant;

use App\Facades\Feature;
use Mtc\MercuryDataModels\Dealership;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\VehicleReservations\VehicleMoveRequest;
use Tests\TenantTestCase;
use Tests\UserForTenant;

class VehicleMoveRequestControllerTest extends TenantTestCase
{
    use UserForTenant;

    private function enableFeature(): void
    {
        Feature::setEnabled(tenant(), ['vehicle-moves']);
    }

    private function makeMoveRequest(array $attributes = [], bool $paid = true): VehicleMoveRequest
    {
        $from = Dealership::factory()->create();
        $to = Dealership::factory()->create();
        $vehicle = Vehicle::factory()->create(['dealership_id' => $from->id]);

        $factory = VehicleMoveRequest::factory();
        if ($paid) {
            $factory = $factory->paid();
        }

        return $factory->create(array_merge([
            'vehicle_id' => $vehicle->id,
            'from_dealership_id' => $from->id,
            'to_dealership_id' => $to->id,
        ], $attributes));
    }

    public function testIndexIsForbiddenWhenTheFeatureIsDisabled(): void
    {
        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->getJson(route('tenant.vehicle-move-requests.index'));

        $response->assertStatus(401);
    }

    public function testIndexReturnsOnlyPaidRequests(): void
    {
        $this->enableFeature();
        $paid = $this->makeMoveRequest();
        $pending = $this->makeMoveRequest([], paid: false);

        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->getJson(route('tenant.vehicle-move-requests.index'));

        $response->assertStatus(200);
        $ids = collect($response->json('data'))->pluck('id');
        $this->assertTrue($ids->contains($paid->id));
        $this->assertFalse($ids->contains($pending->id));
    }

    public function testShowReturnsTheMoveRequest(): void
    {
        $this->enableFeature();
        $moveRequest = $this->makeMoveRequest();

        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->getJson(route('tenant.vehicle-move-requests.show', $moveRequest));

        $response->assertStatus(200);
        $response->assertJsonFragment(['reference' => $moveRequest->reference]);
    }

    public function testDestroyCancelsTheMoveRequest(): void
    {
        $this->enableFeature();
        $moveRequest = $this->makeMoveRequest();

        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->deleteJson(route('tenant.vehicle-move-requests.destroy', $moveRequest));

        $response->assertStatus(200);
        $this->assertEquals('cancelled', $moveRequest->fresh()->status);
    }
}
