<?php

namespace App\Crm;

use App\Contracts\AddsDealershipFields;
use App\Contracts\ForwardsReservationToCrm;
use App\Contracts\ForwardsServiceBookingToCrm;
use App\Facades\Settings;
use App\Services\DealerWebLmsApi;
use Mtc\Crm\Contracts\EnquiryAction;
use Mtc\Crm\Contracts\EnquiryActionModel;
use Mtc\Crm\Contracts\EnquiryModel;
use Mtc\MercuryDataModels\Booking;
use Mtc\VehicleReservations\Reservation;

class SendToDealerWebLms implements
    EnquiryAction,
    AddsDealershipFields,
    ForwardsReservationToCrm,
    ForwardsServiceBookingToCrm
{
    use CheckForExpiredAction;

    public function __construct(private DealerWebLmsApi $api)
    {
        //
    }

    public function enabled(): bool
    {
        return Settings::get('dealerweblms-crm-enabled') === true;
    }

    /**
     * Data fields to add to form
     *
     * @return array
     */
    public function formAdditionalDataFields(): array
    {
        return [
            'lead-type' => [
                'type' => 'text',
                'label' => 'DealerWeb LeadType override (e.g. NWC, USE, SVC). '
                    . 'Leave blank to derive from enquiry context.',
            ],
        ];
    }

    /**
     * Data fields to add to dealership
     *
     * @return array
     */
    public function dealershipAdditionalDataFields(): array
    {
        return [
            'dealerweb-dealer-id' => [
                'type' => 'text',
                'label' => 'DealerWeb Dealer ID',
            ],
            'dealerweb-username' => [
                'type' => 'text',
                'label' => 'DealerWeb LMS Username (optional)',
            ],
        ];
    }

    /**
     * Data fields to add to questions
     *
     * @return array[]
     */
    public function formQuestionDataFields(): array
    {
        return [
            'dealer-web-lms-field' => [
                'type' => 'select',
                'label' => 'Field mapped against Dealer Web LMS',
                'choices' => [
                    'DealerNo' => 'Dealer Number (Manufacturer’s dealer number)',
                    'ThirdParty' => 'Third Party Name (Supplier of the lead)',
                    'LeadType' => "Lead type",
                    'Title' => 'Title',
                    'Forename' => 'Forename',
                    'Surname' => 'Surname',
                    'FullName' => 'Full Name (If supplied, split into Forename and Surname)',
                    'Salutation' => 'Salutation',
                    'Company' => 'Company Name',
                    'HouseNameNo' => 'House Name/No.',
                    'Street' => 'Street',
                    'Locale' => 'Suburb/Locale/District',
                    'City' => 'City',
                    'Postcode' => 'Postcode',
                    'Tel_Home' => 'Home Phone Number',
                    'Tel_Mobile' => 'Mobile Phone Number',
                    'Tel_Work' => 'Work Phone Number',
                    'Email' => 'Email Address',
                    'Franchise' => 'Franchise',
                    'Model' => 'Model (The model the customer is enquiring about)',
                    'NewUsed' => 'New or used',
                    'PexMake' => 'Part Exchange Vehicle Make',
                    'PexModel' => 'Part Exchange Vehicle Model',
                    'PexRegNo' => 'Part Exchange Vehicle Registration Number',
                    'PexMileage' => 'Part Exchange Vehicle Mileage',
                    'include_in_details_content' => 'Add to additional lead details',
                    'URL' => 'External URL for additional vehicle details (must start with https://)',
                ],
            ]
        ];
    }

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

        $leadTypeOverride = trim((string) ($action->data['lead-type'] ?? '')) ?: null;

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

    public function sendReservation(Reservation $reservation): bool
    {
        return $this->api->sendReservation($reservation);
    }

    /**
     * Message when successfully processed
     *
     * @return string
     */
    public function successDetails(): string
    {
        return $this->api->getResponseMessage();
    }

    /**
     * Message when failure detected
     *
     * @return string
     */
    public function failureReason(): string
    {
        return $this->api->getResponseMessage() ?? 'Unknown error';
    }

    public function sendServiceBooking(Booking $booking): bool
    {
        return $this->api->sendServiceBooking($booking);
    }
}
