<?php

namespace App\Crm;

use App\Crm\Config\DealerKitCrmConfig;
use App\Services\DealerKitApi;
use Mtc\Crm\Contracts\EnquiryAction;
use Mtc\Crm\Contracts\EnquiryActionModel;
use Mtc\Crm\Contracts\EnquiryModel;

class SendEnquiryToDealerKit implements EnquiryAction
{
    use CheckForExpiredAction;

    public function __construct(
        private readonly DealerKitApi $api,
        private readonly DealerKitCrmConfig $config
    ) {
    }

    public function enabled(): bool
    {
        return $this->config->enabled();
    }

    public function formAdditionalDataFields(): array
    {
        return [];
    }

    public function formQuestionDataFields(): array
    {
        return [
            'dealerkit-field' => [
                'type' => 'select',
                'label' => 'Field mapped against DealerKit',
                'choices' => [
                    'person.title' => 'Title',
                    'person.first_name' => 'First Name',
                    'person.last_name' => 'Last Name',
                    'person.company_name' => 'Company Name',
                    'person.email' => 'Email Address',
                    'person.telephone' => 'Telephone',
                    'preferredContactMethods' => 'Preferred means of contact',
                    'message.plain' => 'Message/Comments',
                    'note' => 'Internal Note',
                ],
            ],
        ];
    }

    public function handle(EnquiryActionModel $action, EnquiryModel $enquiry): ?bool
    {
        if ($this->expired($action)) {
            return null;
        }

        return $this->api->sendLead($enquiry, $action);
    }

    public function successDetails(): string
    {
        $reference = $this->api->getResponseAttribute('data.id');
        return $reference
            ? __('crm.lead_registered_with_reference', ['reference' => $reference])
            : __('crm.lead_registered');
    }

    public function failureReason(): string
    {
        if ($skipped = $this->api->getSkippedReason()) {
            return $skipped;
        }

        $status = $this->api->getResponseStatus();
        $message = $this->api->getResponseAttribute('message');

        if ($status === 422) {
            $errors = $this->api->getResponseAttribute('errors');
            if (is_array($errors) && !empty($errors)) {
                $formatted = [];
                foreach ($errors as $field => $messages) {
                    $formatted[] = $field . ': ' . implode('; ', (array) $messages);
                }
                return ($message ? $message . ' — ' : '') . implode(' | ', $formatted);
            }
        }

        if ($message) {
            return (string) $message;
        }

        return $status
            ? __('crm.dealerkit.returned_http', ['status' => $status])
            : __('crm.unknown_error');
    }
}
