<?php

namespace App\Jobs;

use App\Exports\CarsIrelandExport;
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 CarsIrelandExportJob 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-cars-ireland-ftp-username', '');
        $this->ftpPassword = Settings::get('sales-channels-cars-ireland-ftp-password', '');
    }

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

            SalesChannelHistory::store(
                'cars-ireland',
                true,
                $export->collection()->count() . ' records exported',
                null,
                $export->collection()->map(fn($row) => [
                    'uuid' => $row['adid'],
                    'vrm' => $row['regnumber'],
                    'price' => $row['price'],
                    'image count' => null
                ])->toArray()
            );
        } catch (Exception $exception) {
            SalesChannelHistory::store('cars-ireland', false, $exception->getMessage());
        }
    }
}
