<?php

namespace App\Jobs;

use App\Exports\EasiChatFeedExport;
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 Maatwebsite\Excel\Facades\Excel;
use Mtc\MercuryDataModels\SalesChannelHistory;

class EasiChatExportJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public function __construct()
    {
        $this->onQueue('export');
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            $export = new EasiChatFeedExport();

            $fileName = 'easichat_stock.csv';

            Excel::store(
                $export,
                "feeds/channel-feed/" . $fileName,
                'file-storage'
            );

            SalesChannelHistory::store('easichat', true, $export->query()->count() . ' records exported');
        } catch (Exception $exception) {
            SalesChannelHistory::store('easichat', false, $exception->getMessage());
        }
    }
}
