<?php

namespace App\Jobs;

use App\Exports\CarWowExport;
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 CarWowExportJob 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');
        $this->ftpUsername = Settings::get('sales-channels-car-wow-ftp-username', '');
        $this->ftpPassword = Settings::get('sales-channels-car-wow-ftp-password', '');
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            Config::set('filesystems.disks.car-wow-export.username', $this->ftpUsername);
            Config::set('filesystems.disks.car-wow-export.password', $this->ftpPassword);
            $export = new CarWowExport();
            Excel::store(
                $export,
                Settings::get('sales-channels-car-wow-file-name'),
                'car-wow-export'
            );

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