<?php

namespace App\Jobs;

use App\Exports\CarzoneExport;
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 CarzoneExportJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

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

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            Config::set(
                'filesystems.disks.carzone-export.username',
                Settings::get('sales-channels-carzone-ftp-username')
            );
            Config::set(
                'filesystems.disks.carzone-export.password',
                Settings::get('sales-channels-carzone-ftp-password')
            );
            $export = new CarzoneExport();

            Excel::store(
                $export,
                Settings::get('sales-channels-carzone-file-name'),
                'carzone-export'
            );
            SalesChannelHistory::store(
                'carzone',
                true,
                $export->collection()->count() . ' records exported',
                null,
                $export->collection()->map(fn ($row) => [
                    'uuid' => $row['vehicleid'],
                    'vrm' => $row['registration'],
                    'price' => $row['price'],
                    'image count' => substr_count($row['picturerefs'] ?? '', ',')
                ])->toArray()
            );
        } catch (Exception $exception) {
            SalesChannelHistory::store('carzone', false, $exception->getMessage());
        }
    }
}
