<?php

namespace App\Crm;

use Mtc\Crm\Contracts\EnquiryModel;
use Mtc\Crm\Models\FormQuestion;

trait EnquiryDataToProviderData
{
    private function convertEnquiryToParams(EnquiryModel $enquiry, string $provider): array
    {
        // Use normalized answers (new table with fallback to legacy details)
        $normalizedAnswers = $enquiry->getNormalizedAnswers();
        $answers = $normalizedAnswers->keyBy('question_id')->map(fn ($item) => $item['answer']);

        return FormQuestion::query()
            ->whereIn('id', $answers->keys())
            ->get()
            ->keyBy('id')
            ->map(fn ($question) => $question->data[$provider] ?? null)
            ->filter()
            ->groupBy(fn ($field) => $field, true)
            ->map(fn ($group) => $group->count() == 1
                ? $answers[$group->keys()->first()] ?? null
                : $group->map(fn ($key, $item) => $answers[$item] ?? null)->filter()->implode(', '))
            ->toArray();
    }

    /**
     * Convert enquiry to params merged with mapped data for each attached object
     * (vehicle, offer, new-car, valuation). Requires the using class to implement
     * any of mapVehicle/mapOffer/mapNewCar/mapValuation it cares about.
     */
    private function convertEnquiryWithObjectsToParams(EnquiryModel $enquiry, string $provider): array
    {
        $params = $this->convertEnquiryToParams($enquiry, $provider);

        foreach ($enquiry->objects as $object) {
            if (empty($object->object)) {
                continue;
            }
            $objectData = match ($object->object_type) {
                'vehicle' => method_exists($this, 'mapVehicle') ? $this->mapVehicle($object->object) : [],
                'offer' => method_exists($this, 'mapOffer') ? $this->mapOffer($object->object) : [],
                'new-car' => method_exists($this, 'mapNewCar') ? $this->mapNewCar($object->object) : [],
                'valuation' => method_exists($this, 'mapValuation') ? $this->mapValuation($object->object) : [],
                default => [],
            };
            $params = array_merge($params, $objectData);
        }

        return $params;
    }

    /**
     * Normalise preferredContactMethods from a CRM params array into a lowercased
     * list of contact methods. Accepts string (CSV), array, or empty/missing.
     */
    private function parseContactMethods(array $params, string $key = 'preferredContactMethods'): array
    {
        if (empty($params[$key])) {
            return [];
        }
        if (is_string($params[$key])) {
            return explode(',', strtolower($params[$key]));
        }
        if (is_array($params[$key])) {
            return array_map(fn ($item) => strtolower((string) $item), $params[$key]);
        }
        return [];
    }
}
