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