<?php

namespace App\Console\Commands;

use App\Facades\Settings;
use Illuminate\Console\Command;
use Mtc\MercuryDataModels\VehicleAutoTraderData;

class BackfillAutoTraderPublishFlags extends Command
{
    protected $signature = 'auto-trader:backfill-publish-flags';

    protected $description = 'Backfill null publish_advert/publish_profile values for AT';

    public function handle(): void
    {
        if (Settings::get('sales-channels-auto-trader-enabled') === false) {
            $this->info('AutoTrader sales channel is disabled — skipping backfill.');
            return;
        }

        $updated = VehicleAutoTraderData::query()
            ->where(function ($query) {
                $query->whereNull('publish_advert')
                    ->orWhereNull('publish_profile');
            })
            ->with('vehicle')
            ->get()
            ->filter(fn($record) => $record->vehicle !== null)
            ->each(function ($record) {
                $updates = [];

                if (is_null($record->publish_advert)) {
                    $updates['publish_advert'] = $record->vehicle->is_new
                        ? (bool) Settings::get('auto-trader-connect-publish-new-cars')
                        : (bool) Settings::get('auto-trader-connect-publish-used-cars');
                }

                if (is_null($record->publish_profile)) {
                    $updates['publish_profile'] = $record->vehicle->is_new
                        ? (bool) Settings::get('auto-trader-connect-profile-new-cars')
                        : (bool) Settings::get('auto-trader-connect-profile-used-cars');
                }

                if (!empty($updates)) {
                    $record->update($updates);
                }
            })
            ->count();

        $this->info("{$updated} vehicle_autotrader_data records updated.");
    }
}
