<?php

namespace App\Modules\Stock\CustomEndpoint;

use App\Facades\Settings;
use App\Traits\EnsuresVehicleAttribute;
use App\Traits\MapsTaxonomies;
use App\Traits\TracksImportStats;
use App\Traits\VehicleRegistrationDateFinderTrait;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Mtc\MercuryDataModels\Vehicle;

class PCKReservedFeed
{
    use DispatchesJobs;
    use MapsTaxonomies;
    use VehicleRegistrationDateFinderTrait;
    use EnsuresVehicleAttribute;
    use TracksImportStats;

    public function handle(): void
    {
        $this->resetStats();
        $settings = json_decode(Settings::get('custom-data-feed-secrets'));
        if (empty($settings->host) || empty($settings->username)) {
            Log::error('unable to perform PCK file sync due to missing credentials');
            return;
        }
        $this->updateVehicles($this->loadFile($settings));
    }

    protected function getProviderName(): string
    {
        return 'pck';
    }

    private function loadFile(object $settings): Collection
    {
        $disk = Storage::build([
            'driver' => 'sftp',
            'root' => $settings->homePath,
            'host' => $settings->host,
            'username' => $settings->username,
            'password' => $settings->password,
        ]);

        return collect($disk->files())
            ->keyBy(fn ($path) => $path)
            ->map(fn ($path) => $disk->get($path))
            ->map(fn ($data) => $this->processFileData($data))
            ->flatMap(fn ($value, $index) => $value);
    }

    private function updateVehicles(Collection $vehicleList): void
    {
        $vehicleList->filter(fn ($entry) => $entry)
            ->chunk(20)
            ->each(function ($chunk) {
                $updated = Vehicle::query()->whereIn('vin', $chunk->keys())->update(['is_reserved' => true]);
                for ($i = 0; $i < $updated; $i++) {
                    $this->incrementUpdated();
                }
            });

        Vehicle::query()
            ->whereNotNull('stock_provider')
            ->whereNotIn('vin', $vehicleList->keys())
            ->delete();
    }

    private function processFileData($data): Collection
    {
        return collect(explode(PHP_EOL, (string) $data))
            ->skip(1)
            ->map(fn ($row) => explode(",", $row))
            ->filter(fn ($row) => count($row) == 22)
            ->keyBy(fn ($row) => $row[2])
            ->map(fn ($row) => $row[20] == 'Reserved');
    }
}
