<?php

namespace Tests\Tenant;

use App\Facades\Settings;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use Mtc\MercuryDataModels\Dealership;
use Tests\Data\FinanceSettingSeeder;
use Tests\TenantTestCase;

class CapFinanceWithDealershipTest extends TenantTestCase
{
    public function testCapFinanceUsesDealershipCodeWeaversCode()
    {
        Http::fake([
            'https://services.codeweavers.net/*' => Http::response($this->codeWeaversResponse()),
        ]);

        $this->seedCodeWeaversSettings('fallback-dealer');

        $dealership = Dealership::factory()->create([
            'data' => ['codeweavers' => 'dealership-specific-code'],
            'location_finance' => 'dealership-loc-finance',
        ]);

        $this->postJson(route('vehicles.get-cap-finance'), [
            'cap_id' => 'CAP123',
            'price' => 25000,
            'term' => 48,
            'deposit' => 2500,
            'annual_mileage' => 10000,
            'credit_rating' => 'excellent',
            'dealership_id' => $dealership->id,
        ]);

        Http::assertSent(function (Request $request) {
            return $request['VehicleRequests'][0]['Dealer'] === 'dealership-specific-code';
        });
    }

    public function testCapFinanceUsesFallbackWhenNoDealershipProvided()
    {
        Http::fake([
            'https://services.codeweavers.net/*' => Http::response($this->codeWeaversResponse()),
        ]);

        $this->seedCodeWeaversSettings('fallback-dealer');

        $this->postJson(route('vehicles.get-cap-finance'), [
            'cap_id' => 'CAP123',
            'price' => 25000,
            'term' => 48,
            'deposit' => 2500,
            'annual_mileage' => 10000,
            'credit_rating' => 'excellent',
        ]);

        Http::assertSent(function (Request $request) {
            return $request['VehicleRequests'][0]['Dealer'] === 'fallback-dealer';
        });
    }

    public function testCapFinanceUsesFallbackWhenDealershipHasNoCodeWeaversCode()
    {
        Http::fake([
            'https://services.codeweavers.net/*' => Http::response($this->codeWeaversResponse()),
        ]);

        $this->seedCodeWeaversSettings('fallback-dealer');

        $dealership = Dealership::factory()->create([
            'data' => [],
        ]);

        $this->postJson(route('vehicles.get-cap-finance'), [
            'cap_id' => 'CAP123',
            'price' => 25000,
            'term' => 48,
            'deposit' => 2500,
            'annual_mileage' => 10000,
            'credit_rating' => 'excellent',
            'dealership_id' => $dealership->id,
        ]);

        Http::assertSent(function (Request $request) {
            return $request['VehicleRequests'][0]['Dealer'] === 'fallback-dealer';
        });
    }

    private function seedCodeWeaversSettings(string $dealerName): void
    {
        $this->seed(FinanceSettingSeeder::class);
        Settings::update('finance-codeweavers-enabled', true);
        Settings::update('finance-codeweavers-api_key', 'test-api-key');
        Settings::update('finance-codeweavers-username', 'test-user');
        Settings::update('finance-codeweavers-password', 'test-pass');
        Settings::update('finance-codeweavers-dealer_name', $dealerName);
        Settings::update('finance-front-end-calculator-enabled', true);
    }

    private function codeWeaversResponse(): array
    {
        return [
            'VehicleResults' => [
                [
                    'FinanceProductResults' => [
                        [
                            'Product' => [
                                'Type' => 'PCP',
                                'Name' => 'test',
                            ],
                            'Quote' => [
                                'AllInclusiveRegularPayment' => 250,
                                'Term' => 48,
                                'Apr' => 8.9,
                                'TotalDeposit' => 2500,
                                'CashDeposit' => 2500,
                                'Deposit' => 2500,
                                'FinalPayment' => 10000,
                                'RateOfInterest' => 8,
                                'CashPrice' => 25000,
                                'TotalAmountPayable' => 28000,
                                'Payments' => [
                                    ['Amount' => 250, 'NumberOfPayments' => 47],
                                ],
                                'Fees' => [],
                            ],
                        ],
                    ],
                ],
            ],
        ];
    }
}
