<?php

namespace App\Modules\Leasing;

use App\Modules\Leasing\Jobs\ImportDiscountsJob;
use Illuminate\Support\Collection;
use Mtc\MercuryDataModels\KeyloopLeaseDiscount;
use Mtc\MercuryDataModels\KeyloopLeaseVehicleVariant;

class KeyloopFleetKompactDiscountImporter extends KeyloopFleetKompactImporterBase
{
    protected array $filtered_variants = [];

    protected function filter(Collection $data): bool
    {
        return $this->makeModelEligibleForImport($data);
    }

    protected function makeModelEligibleForImport(Collection $data): bool
    {
        return array_key_exists((string) $data['fran'], $this->enabled_keyloop_makes)
            && array_key_exists($data['fran'], $this->enabled_keyloop_models)
            && (
                array_key_exists((string) $data['model'], $this->enabled_keyloop_models[$data['fran']])
                || empty($data['model'])
            );
    }

    protected function prepareForImport(): void
    {
        KeyloopLeaseDiscount::query()->update([
            'was_recently_synced' => false,
        ]);
    }

    protected function importItems(Collection $data): void
    {
        $this->dispatch(new ImportDiscountsJob($data->map(function ($item) {
            $discount = $this->getDiscount($item);
            return [
                'external_variant_id' => $item['variant'],
                'make_id' => $this->getVehicleMake($item['fran']),
                'model_id' => $this->getVehicleModel($item['model'], $item['fran']),
                'discount_type' => $discount['type'],
                'discount_amount' => $discount['amount'],
            ];
        })));
    }

    private function getDiscount(Collection $item): array
    {
        $type = '';
        $amount = 0;

        if (strtoupper((string) $item['type']) == 'BONUS') {
            $type = 'cash';
            $amount = $item['bonus'];
        } elseif (strtoupper((string) $item['type']) == 'DISCOUNT') {
            $type = 'percentage';
            $amount = $item['disc'];
        }

        return [
            'type' => $type,
            'amount' => $amount,
        ];
    }
}
