<?php

namespace App\Console\Commands;

use App\Facades\Settings;
use App\Modules\ImageSync\AutoloadIt;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Mtc\MercuryDataModels\ApiNotification;

class BackfillAutoloadItImagesInNotifications extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'backfill-autoload-it-images-in-notifications';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Adds records of old AutoloadIt file entries in api_notifications table for processing';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $files = collect(Storage::disk('autoloadit-images-import')->files())
            ->reverse()
            ->filter(fn($file) => Str::endsWith($file, '.old'))
            ->each(fn($file) => $this->processImageFile($file));
    }

    private function processImageFile(string $file): void
    {
        try {
            $file_contents = explode("\r\n", (string) Storage::disk('autoloadit-images-import')->get($file));
            $headings = str_getcsv(array_shift($file_contents), escape: '\\');
            $collection = collect($file_contents)
                ->map(fn($row) => collect(str_getcsv($row, escape: '\\'))
                    ->keyBy(fn($value, $index) => strtolower((string) $headings[$index])))
                ->filter(fn($vehicle) => Settings::get('image-sync-autoloadit-feed-id') == ($vehicle['feed_id'] ?? ''))
                ->each(fn($vehicle) => $this->addIfNotExists($vehicle));
        } catch (\Exception $exception) {
            dump($exception);
        }
    }

    private function addIfNotExists($vehicle)
    {
        if (!$this->notificationExists($vehicle['fullregistration'])) {
            ApiNotification::query()
                ->create([
                    'provider' => AutoloadIt::PROVIDER_NAME,
                    'data_model' => 'vehicle',
                    'reference' => str_replace(' ', '', $vehicle['fullregistration']),
                    'data' => $vehicle,
                    'processed' => 1,
                ]);
        }
    }

    private function notificationExists($vrm): bool
    {

        return ApiNotification::query()
            ->where([
                'provider' => AutoloadIt::PROVIDER_NAME,
                'data_model' => 'vehicle',
                'reference' => str_replace(' ', '', $vrm),
                'processed' => 1,
            ])
            ->exists();
    }
}
