<?php

namespace App\Jobs;

use App\Exports\VehiclesInVideoExport;
use App\Facades\Settings;
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\Config;
use Maatwebsite\Excel\Facades\Excel;
use Mtc\MercuryDataModels\SalesChannelHistory;

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

    private string $ftpUsername;
    private string $ftpPassword;

    public function __construct()
    {
        $this->onQueue('export');
        $this->ftpUsername = Settings::get('sales-channels-vehicles-in-video-ftp-username', '');
        $this->ftpPassword = Settings::get('sales-channels-vehicles-in-video-ftp-password', '');
    }

    public function handle(): void
    {
        try {
            Config::set('filesystems.disks.vehicles-in-video-export.username', $this->ftpUsername);
            Config::set('filesystems.disks.vehicles-in-video-export.password', $this->ftpPassword);

            $export = new VehiclesInVideoExport();
            Excel::store(
                $export,
                Settings::get('sales-channels-vehicles-in-video-file-name') ?: 'feed.csv',
                'vehicles-in-video-export'
            );

            $rows = $export->collection();
            SalesChannelHistory::store(
                'vehicles-in-video',
                true,
                $rows->count() . ' records exported',
                null,
                $rows->map(fn ($row) => [
                    'vrm' => $row['registration'],
                    'price' => $row['price'],
                    'image count' => substr_count($row['images'] ?? '', ','),
                ])->toArray()
            );
        } catch (Exception $exception) {
            SalesChannelHistory::store('vehicles-in-video', false, $exception->getMessage());
        }
    }
}
