<?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
    {
        if (!isset($this->filtered_variants[$data['variant']])) {
            $this->filtered_variants[$data['variant']] = KeyloopLeaseVehicleVariant::query()
                ->where('was_recently_synced', '=', true)
                ->where('external_variant_id', '=', $data['variant'])
                ->exists();
        }

        if ($this->filtered_variants[$data['variant']]) {
            // always store discounts if we have the variant in stock
            return true;
        }

        return $this->makeModelEligibleForImport($data);
    }

    protected function makeModelEligibleForImport(Collection $data): bool
    {
        return array_key_exists($data['fran'], $this->enabled_keyloop_makes)
            && array_key_exists($data['fran'], $this->enabled_keyloop_models)
            && (
                array_key_exists($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($item['type']) == 'BONUS') {
            $type = 'cash';
            $amount = $item['bonus'];
        } elseif (strtoupper($item['type']) == 'DISCOUNT') {
            $type = 'percentage';
            $amount = $item['disc'];
        }

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