<?php

namespace App\Traits;

use App\Http\Resources\FormViewResource;
use Mtc\MercuryDataModels\Form;

trait GetsFormResource
{
    /**
     * @param Form $form
     * @param array $values
     * @return FormViewResource|null
     */
    protected function getResourceForForm(?Form $form, array $values = []): ?FormViewResource
    {
        return $form
            ? new FormViewResource($form)->setValues($values)
            : null;
    }

    /**
     * @param string $enquiry_type
     * @param string $containing_field_type
     * @param array $values
     * @return FormViewResource|null
     */
    protected function getResourceForFormByEnquiryType(
        string $enquiry_type,
        string $containing_field_type,
        array $values = []
    ): ?FormViewResource {
        $resource = Form::query()
            ->whereHas('type', fn ($query) => $query->where('name', '=', $enquiry_type))
            ->whereHas('questions', fn ($query) => $query->where('type', '=', $containing_field_type))
            ->when(
                !empty($values['dealership_id']),
                fn ($locationQuery) => $locationQuery->where(fn ($query) => $query->whereDoesntHave('dealerships')
                    ->orWhereHas('dealerships', fn ($q) => $q->where('dealership_id', $values['dealership_id'])))
            )
            ->first();

        return $resource
            ? new FormViewResource($resource)->setValues($values)
            : null;
    }
}
