<?php

namespace App\Jobs;

use App\Exports\MotorsCoUkExport;
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 Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Mtc\MercuryDataModels\SalesChannelHistory;

class MotorsCoUkExportJob 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-motors-co-uk-ftp-username') ?? '';
        $this->ftpPassword = Settings::get('sales-channels-car-motors-co-uk-ftp-password') ?? '';
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            Config::set('filesystems.disks.motors-co-uk-export.username', $this->ftpUsername);
            Config::set('filesystems.disks.motors-co-uk-export.password', $this->ftpPassword);
            $export = new MotorsCoUkExport();
            Excel::store(
                $export,
                Settings::get('sales-channels-motors-co-uk-file-name'),
                'motors-co-uk-export'
            );
            // With SFTP accounts we need to check for file existing as put will not throw an error,
            // but exists check will throw an error on failure
            Storage::disk('motors-co-uk-export')->exists(Settings::get('sales-channels-motors-co-uk-file-name'));
            SalesChannelHistory::store(
                'motors-co-uk',
                true,
                $export->collection()->count() . ' records exported',
                null,
                $export->collection()->map(fn ($row) => [
                    'uuid' => $row['Vehicle_ID'],
                    'vrm' => $row['Registration'],
                    'price' => $row['Price'],
                    'image count' => substr_count($row['PictureRefs'] ?? '', ',')
                ])->toArray()
            );
        } catch (Exception $exception) {
            SalesChannelHistory::store('motors-co-uk', false, $exception->getMessage());
        }
    }
}
