<?php

namespace App\Http\Resources;

use App\Crm\EnquiryDataToProviderData;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Mtc\MercuryDataModels\Dealership;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\MercuryDataModels\VehicleValuation;

class StormEnquiryResource extends JsonResource
{
    use EnquiryDataToProviderData;

    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        $params = $this->convertEnquiryToParams($this->resource, 'ms-dynamics-field');
        $contact_methods = explode(',', strtolower($params['contact_methods'] ?? ''));
        $location = $this->getLocation();
        return [
            '_links' => [
                'last' => null,
                'next' => null,
                'self' => '',
            ],
            'context' => [
                'language' => 'en',
                'offer_url' => null,
                'product_url' => null,
                // Site vehicle
                'vehicle' => $this->mapVehicle(),
            ],
            'date_submitted' => $this->created_at->format('Y-m-d H:i:s'),
            'dealer' => [
                'franchise' => [
                    'hash' => null,
                ],
                'group' => [
                    'hash' => null,
                ],
                'location' => [
                    'hash' => $location?->data['ms-dynamics-dealership'] ?? null,
                ],
            ],
            'form' => [
                'customer' => [
                    'address' => [
                        'building_ext' => $params['building_ext'] ?? null,
                        'building_int' => $params['building_int'] ?? null,
                        'country_code' => $params['country_code'] ?? null,
                        'district' => $params['district'] ?? null,
                        'postcode' => $params['postcode'] ?? null,
                        'primary_locality' => $params['primary_locality'] ?? null,
                        'secondary_locality' => $params['secondary_locality'] ?? null,
                        'street' => $params['street'] ?? null,
                    ],
                    'email' => $params['email'] ?? null,
                    'first_name' => $params['first_name'] ?? null,
                    'last_name' => $params['last_name'] ?? null,
                    'marketing_preferences' => [
                        'first_party' => [
                            'email' => in_array('email', $contact_methods),
                            'phone' => in_array('phone', $contact_methods),
                            'post' => in_array('post', $contact_methods),
                            'sms' => in_array('sms', $contact_methods),
                        ]
                    ],
                    'phone' => [
                        'number' => $params['phone'],
                        'type' => null,
                    ],
                    'postcode' => $params['postcode'] ?? null,
                    'title' => $params['title'] ?? null,
                    // Part-ex or service vehicle
                    'vehicle' => $this->mapCustomerVehicle(),

                ],
                'enquiry' => [
                    'configuration' => null,
                    'enquiry_url' => $params['source_url'] ?? null,
                    'group_software_hash' => 'abc123',
                    'message' => $params['message'] ?? null,
                    'offer_price' => null,
                    'order_type' => null,
                    'preferred_date' => $params['preferred_date'] ?? '',
                    'preferred_date_approximate' => $params['preferred_date_approximate'] ?? '',
                    'referring_url' => '',
                ],
            ],
            'guid' => $this->resource->id,
            'type' => [
                'id' => $this->resource->form_id,
                'name' => $this->resource->form?->name,
            ]
        ];
    }

    private function mapCustomerVehicle(): ?array
    {
        $valuation_object = $this->resource->objects->where('object_type', 'valuation')->first();
        if ($valuation_object) {
            return $this->mapValuationVehicle($valuation_object->object);
        }

        $valuation_object = $this->resource->objects->where('object_type', 'service-booking')->first();
        if ($valuation_object) {
//            return $this->mapServiceBookingVehicle($valuation_object->object);
        }

        return null;
    }

    private function mapValuationVehicle(VehicleValuation $valuation): ?array
    {
        return [
            'condition' => 'Used',
            'dealer' => null,
            'derivative' => null,
            'engine_size_litres' => null,
            'fuel_type' => $valuation->fuel_type,
            'manufacturer' => $valuation->make,
            'model' => $valuation->model,
            'next_mot_date' => null,
            'next_service_date' => null,
            'odometer' => [
                'current' => $valuation->mileage,
                'unit' => 'km',
            ],
            'transmission_type' => $valuation->transmissionType,
            'variant' => null,
            'vrm' => $valuation->registration,
        ];
    }

    private function mapVehicle(): ?array
    {
        $vehicle_object = $this->resource->objects->where('object_type', 'vehicle')->first();
        if (!$vehicle_object) {
            return null;
        }

        /** @var Vehicle $vehicle */
        $vehicle = $vehicle_object->object;
        return [
            'condition' => $vehicle->is_new ? 'New' : 'Used',
            'dealer' => null,
            'derivative' => $vehicle->derivative,
            'engine_size_litres' => $vehicle->engine_size_cc
                ? round($vehicle->engine_size_cc / 1000, 2)
                : null,
            'fuel_type' => $vehicle->fuelType?->name,
            'manufacturer' => $vehicle->make?->name,
            'model' => $vehicle->model?->name,
            'next_mot_date' => null,
            'next_service_date' => null,
            'odometer' => $vehicle->odometer_km,
            'price' => $vehicle->price,
            'transmission_type' => $vehicle->transmissionType?->name,
            'variant' => null,
            'vrm' => $vehicle->vrm_condensed,
        ];
    }

    private function getLocation(): ?Dealership
    {
        $related_object = $this->resource->objects->where('object_type', 'dealership')->first();
        if ($related_object) {
            return $related_object->object;
        }

        $related_vehicle = $this->resource->objects->where('object_type', 'vehicle')->first();
        if ($related_vehicle) {
            return $related_vehicle->object?->dealership;
        }

        return null;
    }
}
