<?php

namespace App\Jobs;

use App\Exports\AaCarsDealerExport;
use App\Exports\AaCarsExport;
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 AaCarsExportJob 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-aa-cars-ftp-username', '');
        $this->ftpPassword = Settings::get('sales-channels-aa-cars-ftp-password', '');
    }

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

            SalesChannelHistory::store(
                'aa-cars',
                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()
            );

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