<?php

namespace App\Jobs;

use App\Exports\AutoTraderCSVExport;
use App\Facades\Settings;
use App\Modules\Stock\AutoTraderStock;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Mtc\MercuryDataModels\SalesChannelHistory;

class AutoTraderCSVExportJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    private string $ftpUsername;
    private string $ftpPassword;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->onQueue('export');
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            $export = new AutoTraderCSVExport();
            Excel::store($export, Settings::get('sales-channels-auto-trader-file-name'), 'local');
            Storage::disk('auto-trader-export')
                ->put(
                    Settings::get('sales-channels-auto-trader-file-name'),
                    Storage::disk('local')->get(Settings::get('sales-channels-auto-trader-file-name'))
                );

            SalesChannelHistory::store(
                'auto-trader-sales',
                true,
                $export->collection()->count() . ' records exported',
                null,
                $export->collection()->map(fn ($row) => [
                    'uuid' => $row['Vehicle_ID'],
                    'vrm' => $row['FullRegistration'],
                    'price' => $row['price'],
                    'image count' => substr_count($row['picturerefs'] ?? '', ',')
                ])->toArray()
            );
            SyncVehicleAutoTraderIdAfterCsvExport::dispatch(App::make(AutoTraderStock::class));
        } catch (Exception $exception) {
            SalesChannelHistory::store('auto-trader-sales', false, $exception->getMessage());
            throw $exception;
        }
    }
}
