<?php

namespace App\Crm;

use App\Facades\Settings;
use App\Services\BrevoApi;
use Illuminate\Support\Facades\App;
use Mtc\Crm\Contracts\EnquiryAction;
use Mtc\Crm\Contracts\EnquiryActionModel;
use Mtc\Crm\Contracts\EnquiryModel;

class SendToBrevo implements EnquiryAction
{
    use CheckForExpiredAction;

    private BrevoApi $api;

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

    /**
     * Handle the action
     *
     * @param EnquiryActionModel $action
     * @param EnquiryModel $enquiry
     * @return bool
     */
    public function handle(EnquiryActionModel $action, EnquiryModel $enquiry): bool
    {
        if ($this->expired($action)) {
            return false;
        }
        $this->api = App::make(BrevoApi::class);
        return $this->api->addCustomerToBrevo($enquiry, $action);
    }

    /**
     * Data fields to add to form
     *
     * @return array
     */
    public function formAdditionalDataFields(): array
    {
        return [
            'brevo_list_id' => [
                'type' => 'text',
                'validation' => [
                    'required',
                    'array',
                ],
                'label' => 'List ID'
            ],
            'brevo_update_enabled' => [
                'type' => 'checkbox',
                'validation' => [
                    'sometimes'
                ],
                'label' => 'Update if the contact already exists'
            ],
        ];
    }

    /**
     * Data fields to add to questions
     *
     * @return array[]
     */
    public function formQuestionDataFields(): array
    {
        return [
            'brevo-field' => [
                'type' => 'select',
                'label' => 'Field mapped against Brevo',
                'choices' => [
                    'EMAIL' => 'Email Address',
                    'FIRSTNAME' => 'First Name',
                    'LASTNAME' => 'Last Name',
                    'APPOINTMENT_DATE' => 'Appointment Date',
                    'APPOINTMENT_TIME' => 'Appointment Time',
                    'VEHICLE_MODEL' => 'Model (The model the customer is enquiring about)',
                ],
            ]
        ];
    }

    /**
     * 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';
    }
}
