<?php

namespace App\Modules\Stock;

use App\Contracts\StockProvider;
use App\Events\StockSyncFinished;
use App\Facades\Settings;
use App\Imports\KeyloopRev8StockImport;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;

class KeyloopRev8 implements StockProvider
{
    use DispatchesJobs;

    /**
     * Check if enabled
     *
     * @return bool
     */
    public function enabled(): bool
    {
        return Settings::get('stock-keyloop-rev8-enabled', false) ?? false;
    }

    /**
     * Name of the integration
     *
     * @return string
     */
    public function name(): string
    {
        return 'Keyloop Rev8';
    }

    /**
     * Perform a scheduled import task
     *
     * @return void
     */
    public function runScheduledImport(bool $fullSync = true): void
    {
        Config::set('filesystems.disks.autonomy-ftp.username', Settings::get('stock-keyloop-rev8-ftp-username'));
        Config::set('filesystems.disks.autonomy-ftp.password', Settings::get('stock-keyloop-rev8-ftp-password'));
        collect(Storage::disk('autonomy-ftp')->files('files'))
            ->each(fn($file) => Excel::import(
                new KeyloopRev8StockImport(pathinfo($file, PATHINFO_FILENAME)),
                $file,
                'autonomy-ftp'
            ))
            ->each(fn($file) => $this->cleanup($file));
        Event::dispatch(new StockSyncFinished('keyloop-rev8'));
    }

    /**
     * Fields to add to dealership management
     *
     * @return array[]
     */
    public function dealershipAdditionalDataFields(): array
    {
        return [
            'keyloop-rev8-location-id' => [
                'type' => 'text',
                'label' => 'Location code for Keyloop Rev8',
            ],
        ];
    }

    private function cleanup(string $file): void
    {
        if (app()->environment('production') || app()->runningUnitTests()) {
//            Storage::disk('autonomy-ftp')->delete("$file");
        }
    }
}
