<?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\ApiNotification;
use Mtc\MercuryDataModels\MediaUse;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\MercuryDataModels\VehicleFeature;

class AutoTraderHub
{
    private string $token;
    private string $deleteSoldSettingKey = 'automotive-sales-channels-auto-trader-unpublish-sold';
    private string $deleteReservedSettingKey = 'automotive-sales-channels-auto-trader-unpublish-reserved';
    private string $markDeletedAsSoldSettingKey = 'auto-trader-upsert-deleted-mark-sold';


    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(10)
            ->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(10)
            ->post($this->endpoint('bulk-export/' . $reference), [
                'vehicles' => $vehicles->map(fn(Vehicle $vehicle) => $this->mapVehicle($vehicle)),
            ]);

        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),
            ]);

        if ($response->status() > 201) {
            ApiNotification::query()->create([
                'provider' => 'at-hub',
                'data' => $response->json(),
                'data_model' => 'vehicle',
                'reference' => $vehicle->vrm_condensed,
            ]);
        }

        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->dealership->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 ?? 0,
            '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(),
                ];
            }),
            'video_url' => $vehicle->main_video_url,
            'at_disabled' => $this->getVehicleDisabledCondition($vehicle),
            'autotraderAdvert' => $vehicle->data['autotraderAdvert'] ?? null,
            'profileAdvert' => $vehicle->data['profileAdvert'] ?? null,
            'lifecycleState' => $this->getLifecycleState($vehicle),
            'actions' => [
                'generateDescription' => $this->shouldGenerateDescription($vehicle),
                'sortImages' => $this->shouldSortImages($vehicle),
            ]
        ];
    }

    private function getLifecycleState(Vehicle $vehicle): string
    {
        if ($vehicle->deleted_at) {
            if (Settings::get($this->markDeletedAsSoldSettingKey, false) ?? false) {
                return 'SOLD';
            }
            return 'DELETED';
        }

        if (
            ((Settings::get($this->deleteSoldSettingKey, false) ?? false) && $vehicle->is_sold) ||
            ((Settings::get($this->deleteReservedSettingKey, false) ?? false) && $vehicle->is_reserved)
        ) {
            return 'DELETED';
        }

        if ($vehicle->is_sold) {
            return 'SOLD';
        }

        if ($vehicle->is_reserved) {
            return 'SALE_IN_PROGRESS';
        }

        return 'FORECOURT';
    }

    private function shouldGenerateDescription(Vehicle $vehicle): bool
    {
        return (Settings::get('auto-trader-upsert-generate-description', false) ?? false)
            && (empty($vehicle->description) || strlen($vehicle->description) > 4000);
    }

    private function shouldSortImages(Vehicle $vehicle): bool
    {
        return Settings::get('auto-trader-upsert-sort-images', false) ?? false;
    }

    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);
            }
        }
    }

    private function getVehicleDisabledCondition(Vehicle $vehicle): bool
    {
        if (!$vehicle->is_published) {
            return true;
        }

        if (Settings::get('automotive-sales-channels-auto-trader-unpublish-demo') && $vehicle->is_demo) {
            return true;
        }

        if (Settings::get('automotive-sales-channels-auto-trader-unpublish-reserved') && $vehicle->is_reserved) {
            return true;
        }

        if (
            Settings::get('automotive-sales-channels-auto-trader-unpublish-no-images')
            && $vehicle->mediaUses->count() === 0
        ) {
            return true;
        }

        return false;
    }
}
