<?php

namespace App\Jobs;

use App\Exports\ChannelFeedExport;
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 ChannelFeedExportJob 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 {
            $tenant = tenant('id');
            $export = new ChannelFeedExport();
            Excel::store(
                $export,
                "feeds/channel-feed/$tenant.csv",
                'file-storage'
            );

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