<?php

namespace App\Listeners;

use App\Events\NewVehicleImported;
use App\Facades\Settings;

class SetAutoTraderConnectPublishFlag
{
    public function __construct()
    {
        //
    }

    public function handle(NewVehicleImported $event)
    {
        if (Settings::get('sales-channels-auto-trader-enabled') === false) {
            return;
        }

        if ($event->vehicle->autoTraderData()->exists()) {
            return;
        }

        $publishAdvert = $event->vehicle->is_new
            ? (bool) Settings::get('auto-trader-connect-publish-new-cars')
            : (bool) Settings::get('auto-trader-connect-publish-used-cars');

        $publishProfile = $event->vehicle->is_new
            ? (bool) Settings::get('auto-trader-connect-profile-new-cars')
            : (bool) Settings::get('auto-trader-connect-profile-used-cars');

        $event->vehicle->autoTraderData()->create([
            'publish_advert' => $publishAdvert,
            'publish_profile' => $publishProfile,
        ]);
    }
}
