<?php

namespace App\Jobs;

use App\Exports\MotoNovoExport;
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 MotoNovoExportJob 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-moto-novo-ftp-username', '');
        $this->ftpPassword = Settings::get('sales-channels-moto-novo-ftp-password', '');
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            Config::set('filesystems.disks.moto-novo-export.username', $this->ftpUsername);
            Config::set('filesystems.disks.moto-novo-export.password', $this->ftpPassword);
            $export = new MotoNovoExport();
            Excel::store(
                $export,
                Settings::get('sales-channels-moto-novo-file-name'),
                'moto-novo-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('moto-novo-export')->exists(Settings::get('sales-channels-moto-novo-file-name'));
            SalesChannelHistory::store(
                'moto-novo',
                true,
                $export->collection()->count() . ' records exported',
                null,
                $export->collection()->map(fn ($row) => [
                    'uuid' => $row['Vehicle_ID'],
                    'vrm' => $row['VRM'],
                    'price' => $row['Price'],
                    'image count' => substr_count($row['PictureUrls'] ?? '', ',')
                ])->toArray()
            );
        } catch (Exception $exception) {
            SalesChannelHistory::store('moto-novo', false, $exception->getMessage());
        }
    }
}
