<?php

namespace App\Crm;

use App\Facades\Settings;
use App\Modules\VehiclesInVideo\Services\VehiclesInVideoService;
use Mtc\Crm\Contracts\EnquiryAction;
use Mtc\Crm\Contracts\EnquiryActionModel;
use Mtc\Crm\Contracts\EnquiryModel;
use Mtc\MercuryDataModels\Vehicle;

class SendToVehiclesInVideo implements EnquiryAction
{
    use CheckForExpiredAction;

    private ?string $lastStatus = null;
    private ?string $lastReference = null;

    public function __construct(private readonly VehiclesInVideoService $service)
    {
    }

    public function enabled(): bool
    {
        return Settings::get('vehicles-in-video-enabled') === true;
    }

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

        if ($enquiry->reason instanceof Vehicle) {
            $this->lastReference = $enquiry->reason->registration_number;
        }

        $this->lastStatus = $this->service->sendFromEnquiry($enquiry);

        if ($this->lastStatus === null) {
            return false;
        }

        return $this->lastStatus === VehiclesInVideoService::STATUS_SENT;
    }

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

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

    public function successDetails(): string
    {
        return $this->lastReference
            ? "Video request sent for {$this->lastReference}"
            : 'Video request sent';
    }

    public function failureReason(): string
    {
        if ($this->lastStatus === null) {
            return 'Unable to dispatch video request to Vehicles In Video';
        }

        return match ($this->lastStatus) {
            VehiclesInVideoService::STATUS_NOT_FOUND
                => 'No video found for vehicle ' . ($this->lastReference ?? ''),
            VehiclesInVideoService::STATUS_FAILED
                => 'Vehicles In Video API rejected the request',
            default => 'Unknown error',
        };
    }
}
