<?php

namespace App\Jobs;

use App\Exports\CarSnipDealerExport;
use App\Exports\CarSnipExport;
use App\Facades\Settings;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
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 CarSnipExportJob 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-car-snip-ftp-username', '');
        $this->ftpPassword = Settings::get('sales-channels-car-snip-ftp-password', '');
    }

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

            SalesChannelHistory::store(
                'car-snip',
                true,
                $export->collection()->count() . ' records exported',
                null,
                $export->collection()->map(fn($row) => [
                    'uuid' => $row['Vehicle_Id'],
                    'vrm' => $row['FullRegistration'],
                    'price' => $row['Price'],
                    'image count' => substr_count($row['images'] ?? '', ',')
                ])->toArray()
            );

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