<?php

namespace App\Services;

use App\Facades\Settings;
use App\VehicleType;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Mtc\MercuryDataModels\MediaUse;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\MercuryDataModels\VehicleFeature;

class AutoTraderHub
{
    private string $token;

    public function setToken(?string $token): self
    {
        if ($token) {
            $this->token = $token;
        }
        return $this;
    }

    public function initExport(): string
    {
        $response = Http::withHeaders(['authorization' => $this->getToken(), 'accept' => 'application/json'])
            ->timeout(5)
            ->post($this->endpoint("bulk-export"));

        if ($response->failed()) {
            Log::error('failed to export to AutoTraderHub', [
                tenant('id'),
                $response->body(),
            ]);
            throw new \Exception($response->body());
        }

        return $response->json('reference');
    }

    public function bulkExport(string $reference, Collection $vehicles): bool
    {
        $response = Http::withHeaders(['authorization' => $this->getToken(), 'accept' => 'application/json'])
            ->timeout(5)
            ->post($this->endpoint('bulk-export/' . $reference), [
                'vehicles' => $vehicles->map(fn(Vehicle $vehicle) => $this->mapVehicle($vehicle)),
            ]);

        return $response->successful();
    }

    public function triggerExport(string $reference): bool
    {
        $response = Http::withHeaders(['authorization' => $this->getToken(), 'accept' => 'application/json'])
            ->timeout(5)
            ->post($this->endpoint("bulk-export/$reference/start"));

        return $response->successful();
    }

    public function export(Vehicle $vehicle): bool
    {
        $response = Http::withHeaders(['authorization' => $this->getToken(), 'accept' => 'application/json'])
            ->timeout(30)
            ->post($this->endpoint('send-vehicle'), [
                'vehicle' => $this->mapVehicle($vehicle),
            ]);

        return $response->successful();
    }

    private function endpoint(string $path): string
    {
        return config('services.auto-trader-hub.url') . '/api/' . ltrim($path, '/');
    }

    private function mapVehicle(Vehicle $vehicle): array
    {
        return [
            'id' => $vehicle->id,
            'advertiser_id' => $vehicle->delership->data['auto-trader-location-id']
                ?? Settings::get('auto-trader-advertiser-id'),
            'stock_id' => $vehicle->auto_trader_id,
            'condition' => $vehicle->is_new ? 'New' : 'Used',
            'registration_number' => $vehicle->registration_number,
            'description' => $vehicle->description,
            'attention_grabber' => Str::limit($vehicle->attention_grabber, 27),
            'published' => $vehicle->is_published,
            'vin' => $vehicle->vin,
            'make' => $vehicle->make?->name,
            'model' => $vehicle->model?->name,
            'derivative' => $vehicle->derivative,
            'odometer_mi' => $vehicle->odometer_mi,
            'type' => $vehicle->type === VehicleType::CAR->value ? 'Car' : 'Van',
            'trim' => $vehicle->trim,
            'body_type' => $vehicle->bodyStyle?->name,
            'fuel_type' => $vehicle->fuelType?->name,
            'transmission_type' => $vehicle->transmission?->name,
            'drivetrain' => $vehicle->drivetrain?->name,
            'seats' => $vehicle->seats,
            'price' => $vehicle->price,
            'rrp_price' => $vehicle->rrp_price,
            'admin_fee' => $vehicle->admin_fee,
            'doors' => $vehicle->door_count,
            'co2' => $vehicle->co2,
            'colour' => $vehicle->colour,
            'vehicle_length' => $vehicle->vehicle_length,
            'manufacture_year' => $vehicle->manufacture_year,
            'first_registration' => $vehicle->first_registration_date,
            'previous_owner_count' => $vehicle->previous_owner_count,
            'engine_size_cc' => $vehicle->engine_size_cc,
            'battery_capacity_kwh' => $vehicle->battery_capacity_kwh,
            'battery_range' => $vehicle->battery_range,
            'features' => $vehicle->features->map(fn (VehicleFeature $feature) => [
                'name' => $feature->name,
                'type' => $feature->category,
            ]),
            'images' => $vehicle->mediaUses->map(function (MediaUse $mediaUse) {
                return [
                    'media_id' => $mediaUse->media->id,
                    'auto_trader_id' => $mediaUse->media->auto_trader_id,
                    'url' => $mediaUse->media->getOriginalUrlAttribute(true),
                ];
            }),
            'video_url' => $vehicle->main_video_url,
            'autotraderAdvert' => $vehicle->data['autotraderAdvert'] ?? null,
            'profileAdvert' => $vehicle->data['profileAdvert'] ?? null
        ];
    }

    private function getToken(): string
    {
        return $this->token;
    }

    public function createSite()
    {
        $response = Http::timeout(5)
            ->withHeaders([
                'X-Auth' => config('services.auto-trader-hub.api_key')
            ])
            ->post($this->endpoint('create-site'), [
                'advertiser_id' => Settings::get('auto-trader-advertiser-id'),
                'name' => tenant()->name,
                'base_url' => config('app.url'),
                'endpoint' => route('tenant.notifications.auto-trader-hub.store', tenant(), false),
                'external_id' => tenant()->id,
            ]);

        if ($response->successful()) {
            $apiToken = $response->json('api_token');
            if ($apiToken) {
                Settings::update('auto-trader-hub-token', $apiToken);
            }
        }
    }
}
