<?php

namespace App\Http\Resources\Api;

use Carbon\Carbon;
use Illuminate\Http\Resources\Json\JsonResource;
use Mtc\MercuryDataModels\MediaUse;

class VehicleResource extends JsonResource
{
    public static $wrap = '';

    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request): array
    {
        $this->resource->load([
            'mediaUses.media',
            'dealership',
            'specs',
            'features',
            'equipment',
            'financeExamples',
            'labels',
        ]);

        $this->resource->fuel_type = $this->resource->fuelType?->name;
        $this->resource->transmission = $this->resource->transmission?->name;
        $this->resource->body_style = $this->resource->bodyStyle?->name;

        $specs = $this->resource->specs->map(fn ($spec) => [
            'category' => trim($spec->category),
            'description' => $spec->description,
            'value' => $spec->value,
        ]);

        $equipment = $this->resource->equipment
            ->each(fn ($item) => $item->makeHidden([
                'id',
                'vehicle_id',
                'feature_id',
                'vehicle_type',
            ]))
            ->sortBy('category')
            ->values();

        $highlights = $this->resource->features
            ->filter(fn ($feature) => $feature->category === 'Highlight')
            ->pluck('name');

        $features = $this->resource->features
            ->reject(fn ($feature) => $feature->category === 'Highlight')
            ->pluck('name');

        $financeExamples = $this->formatFinanceExamples();

        $mediaUses = $this->resource->mediaUses->map(fn (MediaUse $mediaUse) => [
            'id' => $mediaUse->id,
            'title' => $mediaUse->title,
            'alt_text' => $mediaUse->alt_text,
            'src_large' => $mediaUse->getUrl('large'),
            'src_medium' => $mediaUse->getUrl('medium'),
            'src_thumbnail' => $mediaUse->getUrl('thumbs'),
            'type' => $mediaUse->media->type,
            'interior' => $mediaUse->interior,
            'exterior' => $mediaUse->exterior,
        ]);

        $dealership = $this->resource->dealership?->only([
            'id',
            'slug',
            'name',
            'contact_no',
            'email',
            'city',
        ]);

        if ($this->resource->dealership) {
            $dealership['address'] = collect([
                $this->resource->dealership->address1,
                $this->resource->dealership->address2,
                $this->resource->dealership->city,
                $this->resource->dealership->postcode,
            ])->filter()->implode(', ');
        }

        $labels = $this->resource->labels
            ->map(fn ($label) => [
                'id' => $label->id,
                'name' => $label->name,
                'category' => $label->category ?? '',
                'type' => $label->type ?? '',
                'colour' => $label->data['colour'] ?? null,
                'text_colour' => $label->data['text_colour'] ?? null,
            ]);

        $resource = [
            'id' => $this->resource->id,
            'uuid' => $this->resource->uuid,
            'slug' => $this->resource->slug,
            'title' => $this->resource->title,
            'derivative' => $this->resource->derivative,
            'registration_number' => $this->resource->registration_number,
            'vin' => $this->resource->vin,
            'make' => $this->resource->make,
            'model' => $this->resource->model,
            'manufacture_year' => $this->resource->manufacture_year,
            'colour' => $this->resource->colour,
            'transmission' => $this->resource->transmission,
            'fuel_type' => $this->resource->fuel_type,
            'body_style' => $this->resource->body_style,
            'drivetrain' => $this->resource->drivetrain,
            'type' => $this->resource->type,
            'is_new' => $this->resource->is_new,
            'is_sold' => $this->resource->is_sold,
            'is_reserved' => $this->resource->is_reserved,
            'is_demo' => $this->resource->is_demo,
            'price' => $this->resource->price,
            'original_price' => $this->resource->original_price,
            'previous_price' => $this->resource->previous_price,
            'monthly_price' => $this->resource->monthly_price,
            'rrp_price' => $this->resource->rrp_price,
            'deposit' => $this->resource->deposit,
            'bhp' => $this->resource->bhp,
            'co2' => $this->resource->co2,
            'mpg' => $this->resource->mpg,
            'engine_size_cc' => $this->resource->engine_size_cc,
            'odometer_mi' => $this->resource->odometer_mi,
            'odometer_km' => $this->resource->odometer_km,
            'door_count' => $this->resource->door_count,
            'seats' => $this->resource->seats,
            'wheelbase_mm' => $this->resource->wheelbase_mm,
            'wheelbase_type' => $this->resource->wheelbase_type,
            'gross_vehicle_weight_kg' => $this->resource->gross_vehicle_weight_kg,
            'payload_kg' => $this->resource->payload_kg,
            'previous_owner_count' => $this->resource->previous_owner_count,
            'is_vat_applicable' => $this->resource->is_vat_applicable,
            'is_vat_qualifying' => $this->resource->is_vat_qualifying,
            'attention_grabber' => $this->resource->attention_grabber,
            'main_video_url' => $this->resource->main_video_url,
            'battery_capacity_kwh' => $this->resource->battery_capacity_kwh,
            'battery_charge_time' => $this->resource->battery_charge_time,
            'battery_quick_charge_time' => $this->resource->battery_quick_charge_time,
            'battery_quick_charge_level' => $this->resource->battery_quick_charge_level,
            'battery_range' => $this->resource->battery_range,
            'battery_usable_capacity_kwh' => $this->resource->battery_usable_capacity_kwh,
            'first_registration_date' => $this->resource->first_registration_date
                ? Carbon::parse($this->resource->first_registration_date)->format('Y-m-d')
                : null,
            'description' => $this->resource->description,
            'specs' => $specs,
            'features' => $features,
            'highlights' => $highlights,
            'equipment' => $equipment,
            'media_uses' => $mediaUses,
            'dealership' => $dealership,
            'financeExamples' => $financeExamples,
            'labels' => $labels,
            'age_identifier' => $this->resource->getAgeIdentifier(),
            'monthly_cost_type' => $this->resource->getMonthlyCostType(),
        ];

        return $resource;
    }

    private function formatFinanceExamples(): array
    {
        $financeExamples = [];

        foreach ($this->resource->financeExamples as $financeExample) {
            $financeExamples[$financeExample->finance_type] = [
                'provider' => $financeExample->provider,
                'finance_type' => $financeExample->finance_type,
                'monthly_price' => $financeExample->monthly_price,
                'term' => $financeExample->term,
                'number_of_payments' => $financeExample->number_of_payments,
                'total_deposit' => $financeExample->total_deposit,
                'apr' => $financeExample->apr,
                'first_payment' => $financeExample->first_payment,
                'final_payment' => $financeExample->final_payment,
                'interest_rate' => $financeExample->interest_rate,
                'apply_url' => $financeExample->apply_url,
                'annual_mileage' => $financeExample->annual_mileage,
                'cash_price' => $financeExample->cash_price,
                'dealer_deposit' => $financeExample->dealer_deposit,
                'customer_deposit' => $financeExample->customer_deposit,
                'payable_amount' => $financeExample->payable_amount,
                'option_to_purchase_fee' => $financeExample->option_to_purchase_fee,
                'documentation_fee' => $financeExample->documentation_fee,
                'terms_and_conditions' => $financeExample->terms_and_conditions,
                'total_credit_amount' => $financeExample->total_credit_amount,
                'excess_mileage_charge' => $financeExample->excess_mileage_charge,
            ];
        }

        return $financeExamples;
    }
}
