<?php

namespace App\Jobs;

use App\Exports\CarGurusExport;
use App\Facades\Settings;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
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 CarGurusExportJob 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-gurus-ftp-username', '');
        $this->ftpPassword = Settings::get('sales-channels-car-gurus-ftp-password', '');
    }

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

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