<?php

namespace App\Jobs;

use App\Exports\HeyCarDealerExport;
use App\Exports\HeyCarExport;
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 HeyCarExportJob 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-hey-car-ftp-username', '');
        $this->ftpPassword = Settings::get('sales-channels-hey-car-ftp-password', '');
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            Config::set('filesystems.disks.hey-car-export.username', $this->ftpUsername);
            Config::set('filesystems.disks.hey-car-export.password', $this->ftpPassword);
            $export = new HeyCarExport();
            Excel::store(
                $export,
                Settings::get('sales-channels-hey-car-file-name'),
                'hey-car-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('hey-car-export')->exists(Settings::get('sales-channels-hey-car-file-name'));
            SalesChannelHistory::store(
                'hey-car',
                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['images'] ?? '', ',')
                ])->toArray()
            );

            Excel::store(
                new HeyCarDealerExport(),
                Settings::get('sales-channels-hey-car-dealership-file-name'),
                'hey-car-export'
            );
        } catch (Exception $exception) {
            SalesChannelHistory::store('hey-car', false, $exception->getMessage());
        }
    }
}
