<?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\Enquiry;
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
    {
        return [
            '_meta' => [
                'totalCount' => $this->resource->total(),
                'perPage' => $this->resource->perPage(),
                'pageCount' => $this->resource->lastPage(),
                'currentPage' => $request->input('page', 1),
            ],
            '_links' => [
                'self' => route(
                    'storm-enquiries',
                    ['tenant' => tenant('id'), 'page' => $this->resource->currentPage()]
                ),
                'next' => $this->resource->nextPageUrl(),
                'first' => route('storm-enquiries', ['tenant' => tenant('id'), 'page' => 1]),
                'last' => route('storm-enquiries', ['tenant' => tenant('id'), 'page' => $this->resource->lastPage()]),
            ],
            'items' => collect($this->resource->items())->map(fn($enquiry) => $this->mapEnquiry($enquiry))->toArray()
        ];
    }

    private function mapEnquiry($enquiry): array
    {
        $params = $this->convertEnquiryToParams($enquiry, 'ms-dynamics-field');
        $contact_methods = explode(',', strtolower($params['contact_methods'] ?? ''));
        $location = $this->getLocation($enquiry);
        return [
            'context' => [
                'language' => 'en',
                'offer_url' => null,
                'product_url' => null,
                // Site vehicle
                'vehicle' => $this->mapVehicle($enquiry),
            ],
            'date_submitted' => $enquiry->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'] ?? null,
                        'type' => null,
                    ],
                    'postcode' => $params['postcode'] ?? null,
                    'title' => $params['title'] ?? null,
                    // Part-ex or service vehicle
                    'vehicle' => $this->mapCustomerVehicle($enquiry),

                ],
                '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' => $enquiry->id,
            'type' => [
                'id' => $enquiry->form_id,
                'name' => $enquiry->form?->name,
            ]
        ];
    }

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

        $valuation_object = $enquiry->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(Enquiry $enquiry): ?array
    {
        $vehicle_object = $enquiry->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(Enquiry $enquiry): ?Dealership
    {
        $related_object = $enquiry->objects->where('object_type', 'dealership')->first();
        if ($related_object) {
            return $related_object->object;
        }

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

        return null;
    }
}
