<?php

namespace App\Modules\Leasing;

use App\Contracts\LeaseDataProvider;
use App\Facades\Settings;
use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Support\Facades\Storage;

class KeyloopFleetKompact implements LeaseDataProvider
{
    public function enabled(): bool
    {
        return Settings::get('leasing-keyloop-fleet-kompact-enabled') ?? false;
    }

    public function name(): string
    {
        return 'Keyloop Fleet Kompact';
    }

    public function runScheduledImport(): void
    {
        if (Settings::get('leasing-keyloop-fleet-kompact-enabled') == false) {
            return;
        }

        $disk = $this->configureStorageDisk();

        collect($disk->files(Settings::get('leasing-keyloop-fleet-kompact-ftp-storage-path')))
            ->each(fn($file) => Storage::disk('local')->put($file, $disk->get($file)))
            ->map(fn($filename) => match (pathinfo($filename, PATHINFO_BASENAME)) {
                'JATO_DDvaria.csv' => new KeyloopFleetKompactVariantImporter($filename, 1),
                'JATO_RV.csv' => new KeyloopFleetKompactResidualValueImporter($filename),
                'JATO_DDoptns.csv' => new KeyloopFleetKompactOptionImporter($filename),
                'option_categories.csv' => new KeyloopFleetKompactOptionCategoryImporter($filename),
                'JATO_DDopprc.csv' => new KeyloopFleetKompactOptionPriceImporter($filename),
                'JATO_oprel.csv' => new KeyloopFleetKompactPriceMapImporter($filename),
                'JATO_DDspecs.csv' => new KeyloopFleetKompactVariantOptionMapImporter($filename),
                'JATO_DDcolor.csv' => new KeyloopFleetKompactColourImporter($filename),
                'JATO_FQdiscs.csv' => new KeyloopFleetKompactDiscountImporter($filename),
                default => null,
            })
            ->filter(fn($importer) => is_a($importer, KeyloopFleetKompactImporterBase::class))
            ->sortBy(fn(KeyloopFleetKompactImporterBase $importer) => $importer->sort_order)
            ->each(function (KeyloopFleetKompactImporterBase $importer) {
                $importer->importFile();
                $this->cleanup($importer->filename);
            });
    }

    protected function configureStorageDisk(): Filesystem
    {
        return Storage::build([
            'driver' => 'ftp',
            'host' => Settings::get('leasing-keyloop-fleet-kompact-ftp-host'),
            'username' => Settings::get('leasing-keyloop-fleet-kompact-ftp-username'),
            'password' => Settings::get('leasing-keyloop-fleet-kompact-ftp-password'),
            'ssl' => null,
        ]);
    }

    private function cleanup(string $file): void
    {
        Storage::disk('local')->delete($file);
    }
}
