<?php

namespace App\Jobs;

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

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            Config::set('filesystems.disks.inventory-export.username', $this->ftpUsername);
            Config::set('filesystems.disks.inventory-export.password', $this->ftpPassword);
            $export = new InventoryExport();

            Excel::store(
                $export,
                Settings::get('sales-channels-inventory-file-name'),
                'inventory-export'
            );

            SalesChannelHistory::store(
                'inventory',
                true,
                $export->collection()->count() . ' records exported',
                null,
                $export->collection()->map(fn ($row) => [
                    'uuid' => $row['Stock #'],
                    'vrm' => $row['VIN'],
                    'price' => $row['List Price'],
                    'image count' => substr_count($row['Photo URLs'] ?? '', ',')
                ])->toArray()
            );
        } catch (Exception $exception) {
            SalesChannelHistory::store('inventory', false, $exception->getMessage());
        }
    }
}
