<?php

namespace App\Modules\Sales\Services;

use App\Exports\SilverBulletExport;
use App\Modules\Sales\Config\SilverBulletConfig;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;
use Mtc\MercuryDataModels\Vehicle;

class SilverBullet
{
    /**
     * SilverBullet constructor
     *
     * @param SilverBulletConfig $config
     */
    public function __construct(protected readonly SilverBulletConfig $config)
    {
        //
    }

    public function enabled(): bool
    {
        return $this->config->enabled();
    }

    /**
     * Fields to add to dealership management
     *
     * @return array[]
     */
    public function dealershipAdditionalDataFields(): array
    {
        return [
            'silver-bullet-disabled' => [
                'type' => 'checkbox',
                'label' => 'Disable SilverBullet flow for this dealership',
            ],
            'silver-bullet-dealer-id' => [
                'type' => 'number',
                'label' => 'Dealership ID on SilverBullet',
            ],
            'silver-bullet-reserve-cost' => [
                'type' => 'number',
                'label' => 'Custom reserve price for vehicles from this dealership',
            ],
        ];
    }

    /**
     * Export Vehicle collection to SB
     *
     * @return bool
     */
    public function export(): bool
    {
        try {
            Config::set('filesystems.disks.silver-bullet.username', $this->config->ftpUsername());
            Config::set('filesystems.disks.silver-bullet.password', $this->config->ftpPassword());
            $export = new SilverBulletExport();
            Excel::store($export, $this->config->exportFilename(), 'silver-bullet');

            if (config('services.silver-bullet.store-export-logs')) {
                Excel::store($export, 'export/silver-bullet/' . $this->config->exportFilename(), 'file-storage');
            }
        } catch (\Exception $exception) {
            Log::error('Failed to export to SilverBullet ' . tenant('name'), [
                $exception->getMessage(),
            ]);
            return false;
        }
        return true;
    }

    /**
     * Create ecommerce data array
     *
     * @param Vehicle $vehicle
     * @param string $medium
     * @return array
     */
    public function ecommerceData(Vehicle $vehicle, string $medium = 'FPA'): array
    {
        return [
            'vehicle_id' => $vehicle->id,
            'dealer_id' => $vehicle->dealership->location_stock ?? $vehicle->dealership->name,
            'term' => $this->config->term(),
            'deposit' => $this->config->deposit(),
            'annual_mileage' => $this->config->annualMileage(),
            'storefront_base_url' => $this->dealUrl($medium)
        ];
    }

    /**
     * Create url with all required metadata
     *
     * @param string $medium
     * @return string
     */
    public function dealUrl(string $medium)
    {
        return $this->config->domain() . '?'
            . http_build_query([
                'utm_source' => $this->config->siteName(),
                'utm_medium' => $medium,
                'utm_campaign' => $this->config->campaignName(),
            ]);
    }
}
