<?php

namespace App\Jobs;

use App\IntegrationRepository;
use App\Modules\Sales\Services\SilverBullet;
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\App;
use Illuminate\Support\Facades\Log;
use Mtc\MercuryDataModels\Tenant;

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

    public $tries = 2;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(private readonly Tenant $tenant)
    {
        $this->onQueue('export');
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        tenancy()->initialize($this->tenant->id);
        if ((new IntegrationRepository())->isEnabled('silver-bullet') !== true) {
            return;
        }

        try {
            App::make(SilverBullet::class)->export();
        } catch (\Exception $exception) {
            Log::error(
                'SilverBullet Export failed with exception: ' . $exception->getMessage(),
                $exception->getTrace()
            );
        }
    }
}
