<?php

namespace Tests\Tenant;

use App\Facades\Settings;
use Mtc\Crm\Models\EnquiryType;
use Mtc\MercuryDataModels\Form;
use Mtc\MercuryDataModels\KeyloopLeaseVehicleVariant;
use Tests\TenantTestCase;

class LeaseVehicleActionTest extends TenantTestCase
{

    /**
     * Test lease vehicle actions, using form id setting.
     *
     * @return void
     */
    public function testActionEndpointBySetting()
    {
        Settings::make([
            'tab' => 'Automotive',
            'section' => 'General',
            'group' => 'Lease Vehicles',
            'name' => 'Lease Vehicle page enquiry form',
            'config_key' => 'lease-vehicle-enquiry-form-id',
            'type' => 'string',
            'value' => null,
            'source' => 'forms',
        ]);

        $vehicle = KeyloopLeaseVehicleVariant::factory()->create();

        $enquiry_type = EnquiryType::factory()->create([
            'name' => 'Lease Vehicle Enquiry',
        ]);

        // fallback form
        Form::factory()->create([
            'is_active' => true,
            'type_id' => $enquiry_type->id,
        ]);

        $form_target = Form::factory()->create([
            'is_active' => true,
        ]);

        Settings::update('lease-vehicle-enquiry-form-id', $form_target->id);

        $response = $this
            ->getJson(route('lease-vehicles.actions', $vehicle->slug));

        $response->assertStatus(200);

        $this->assertArrayHasKey('actions', $response->json());
        $this->assertArrayHasKey('enquiry', $response->json('actions'));
        $this->assertArrayHasKey('details', $response->json('actions.enquiry'));
        $this->assertEquals($form_target->name, $response->json('actions.enquiry.details.title'));
    }

    /**
     * Test lease vehicle actions, falling back to form type name.
     *
     * @return void
     */
    public function testActionEndpointByName()
    {
        $vehicle = KeyloopLeaseVehicleVariant::factory()->create();

        $enquiry_type = EnquiryType::factory()->create([
            'name' => 'Lease Vehicle Enquiry',
        ]);

        $form = Form::factory()->create([
            'is_active' => true,
            'type_id' => $enquiry_type->id,
        ]);

        $response = $this
            ->getJson(route('lease-vehicles.actions', $vehicle->slug));

        $response->assertStatus(200);

        $this->assertArrayHasKey('actions', $response->json());
        $this->assertArrayHasKey('enquiry', $response->json('actions'));
        $this->assertArrayHasKey('details', $response->json('actions.enquiry'));
        $this->assertEquals($form->name, $response->json('actions.enquiry.details.title'));
    }
}
