<?php

namespace App\Http\Controllers;

use App\Facades\Settings;
use App\Http\Requests\LeaseBulkFinanceRequest;
use App\Http\Requests\LeaseItemFinanceRequest;
use App\Http\Resources\LeaseVehicleFinanceResource;
use App\Http\Resources\LeaseVehicleListFinanceResource;
use Mtc\MercuryDataModels\KeyloopLeaseVehicleVariant;
use Mtc\MercuryDataModels\Leasing\KeyloopLeaseFinanceService;

class LeaseVehicleFinanceController extends Controller
{
    public function getVehicleVariantFinance(KeyloopLeaseVehicleVariant $variant): LeaseVehicleFinanceResource
    {
        $finance = null;

        if (Settings::get('leasing-keyloop-fleet-kompact-enabled')) {
            $finance = new KeyloopLeaseFinanceService()->getVariantFinance($variant);
        }

        return new LeaseVehicleFinanceResource($finance);
    }

    public function getBulkVehicleVariantFinance(LeaseBulkFinanceRequest $request)
    {
        $finance = null;

        if (Settings::get('leasing-keyloop-fleet-kompact-enabled')) {
            $finance = new KeyloopLeaseFinanceService()->getBulkVariantFinance($request->input('variant_slugs'));
        }

        return new LeaseVehicleListFinanceResource($finance);
    }

    public function getBulkItemFinance(KeyloopLeaseVehicleVariant $variant, LeaseItemFinanceRequest $request)
    {
        return collect($request->items)->mapWithKeys(fn ($items, $key) => [
            $key => collect($items)->mapWithKeys(fn ($item) => [
                $item['id'] => array_merge($item, ['finance_options' => $this->getItemFinance($variant, $item)])
            ]),
        ]);
    }

    public function getItemFinance(KeyloopLeaseVehicleVariant $variant, $item)
    {
        return new KeyloopLeaseFinanceService()->getItemFinance($variant, $item);
    }
}
