<?php

namespace App\Http\Resources\VehicleAction;

use App\Facades\Settings;
use App\Http\Resources\FormViewResource;
use Mtc\MercuryDataModels\Form;
use Mtc\MercuryDataModels\Vehicle;

trait LoadsVehicleActions
{
    public function getVehicleActions(Vehicle $vehicle): array
    {
        return [
            'reserve' => $this->reserveAction($vehicle),
            'deal' => $this->salesAction($vehicle),
            'finance' => $this->financeAction($vehicle),
            'enquiry' => $this->enquireAction($vehicle),
            'valuation' => $this->valuationAction($vehicle),
            'eligible_for_risk_based_finance' => $this->riskBasedFinanceEligibilityAction($vehicle),
        ];
    }

    private function valuationAction(Vehicle $vehicle)
    {
        return (new ValuationFactory())->get($vehicle);
    }

    private function enquireAction(Vehicle $vehicle): ?array
    {
        $form = Form::query()
            ->where('is_active', 1)
            ->when(
                Settings::get('vehicle-fpa-form-id'),
                fn($query) => $query->where('id', Settings::get('vehicle-fpa-form-id')),
                fn($query) => $query->whereHas('type', fn($query) => $query->where('name', 'Vehicle Enquiry'))
            )
            ->with('sections.questions')
            ->first();

        return [
            'type' => 'form',
            'title' => 'Make an enquiry',
            'details' => $form
                ? (new FormViewResource($form))->setValues([
                    'vehicle_id' => $vehicle->id,
                    'dealership_id' => $vehicle->dealership_id,
                ])
                : [],
        ];
    }

    private function financeAction(Vehicle $vehicle): bool|array
    {
        return (new FinanceFactory())->get($vehicle);
    }

    private function reserveAction(Vehicle $vehicle): bool|array
    {
        return (new ReserveFactory())->get($vehicle);
    }

    private function riskBasedFinanceEligibilityAction(Vehicle $vehicle): bool
    {
        return (new RiskBasedFinanceEligibilityFactory())->get($vehicle);
    }

    private function salesAction()
    {
        return (new DealFactory())->get(($this->resource));
    }
}
