<?php

namespace App\Console\Commands;

use App\Facades\Settings;
use App\Services\AutoTraderAIApi;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Mtc\MercuryDataModels\Dealership;
use Symfony\Component\Console\Helper\ProgressBar;

class RemoveAllVehiclesFromAutoTraderConnect extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'auto-trader:remove-vehicles';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Remove all vehicles from AutoTrader Connect';

    public function __construct(private readonly AutoTraderAIApi $api)
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $enabled_key = 'sales-channels-auto-trader-enabled';
        $method_key = 'sales-channels-auto-trader-method';
        if (!(Settings::get($enabled_key) && Settings::get($method_key) === 'api')) {
            $this->output->error('Site not configured in AutoTrader Connect mode');
            return self::SUCCESS;
        }

        if ($this->confirm('This command will perform a delete on all AutoTrader adverts. Are you sure?') !== true) {
            $this->output->info('Cancelled');
            return self::SUCCESS;
        }


        $locations = $this->getLocations();
        $this->output->info($locations->count() . ' locations to process');
        $locations->each(fn ($location) => $this->processLocation($location));

        return self::SUCCESS;
    }

    private function getLocations(): Collection
    {
        return  Dealership::all()
            ->map(fn (Dealership $dealership) => $dealership->data['auto-trader-location-id'] ?? null)
            ->filter()
            ->unique();
    }

    private function processLocation(string $location): void
    {
        $stock = $this->getStockRecordsForLocation($location)
            ->filter(fn ($entry) => $entry['metadata']['lifecycleState'] == 'FORECOURT');
        $this->output->info("Processing DID $location with stock items " . $stock->count());
        $progressBar = $this->output->createProgressBar($stock->count());
        $stock->each(fn ($item) => $this->removeStockItem($item, $location, $progressBar));
    }

    private function getStockRecordsForLocation(string $location): Collection
    {
        $params = [
            'pageSize' => 50,
            'advertiserId' => $location,
        ];

        try {
            $data = $this->api->get("stock?" . http_build_query($params));
            if (empty($data['results'])) {
                return collect();
            }
        } catch (\Exception $exception) {
            $this->output->error($exception->getMessage());
            return collect();
        }

        $vehicles = $data['results'];
        if ($data['totalResults'] > 50) {
            $page_count = ceil($data['totalResults'] / 50);
            for ($page = 2; $page <= $page_count; $page++) {
                try {
                    $params['page'] = $page;
                    $url = "stock?" . http_build_query($params);
                    $data = $this->api->get($url);
                    $vehicles = array_merge($vehicles, $data['results']);
                } catch (\Exception $exception) {
                    $this->output->error($exception->getMessage());
                }
            }
        }
        return collect($vehicles);
    }

    private function removeStockItem(array $item, string $location, ProgressBar $progressBar): void
    {
        $progressBar->advance();

        $response = $this->api->deleteVehicle($item['metadata']['stockId'], $location);
        if ($response->failed()) {
            dump($response->json());
        }
        $progressBar->advance();
    }
}
