<?php

namespace App\Modules\Stock;

use App\Contracts\AddsDealershipFields;
use App\Contracts\StockProvider;
use App\Facades\Settings;
use App\Modules\Stock\CustomEndpoint\PCKReservedFeed;
use App\Traits\TracksImportStats;

class CustomEndpoint implements StockProvider, AddsDealershipFields
{
    use TracksImportStats;

    /**
     * Check if enabled
     *
     * @return bool
     */
    public function enabled(): bool
    {
        return Settings::get('stock-endpoint-enabled') ?? false;
    }

    /**
     * Name of the integration
     *
     * @return string
     */
    public function name(): string
    {
        return 'Custom Feed';
    }

    /**
     * Perform a scheduled import task
     *
     * @return void
     */
    public function runScheduledImport(bool $fullSync = true): void
    {
        $this->resetStats();
        $feed = match (Settings::get('stock-endpoint-provider')) {
            'pck' => new PCKReservedFeed(),
            default => null,
        };

        if ($feed) {
            $feed->handle();
            $this->aggregateStats($feed->getImportStats());
        }
    }

    private function aggregateStats(array $stats): void
    {
        for ($i = 0; $i < $stats['created']; $i++) {
            $this->incrementCreated();
        }
        for ($i = 0; $i < $stats['updated']; $i++) {
            $this->incrementUpdated();
        }
        for ($i = 0; $i < $stats['failed']; $i++) {
            $this->incrementFailed();
        }
    }

    /**
     * Fields to add to dealership management
     *
     * @return array[]
     */
    public function dealershipAdditionalDataFields(): array
    {
        return [
            'custom-feed-location-id' => [
                'type' => 'text',
                'label' => 'Dealership ID on stock feed',
            ],
        ];
    }
}
