<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Mtc\MercuryDataModels\NewCar;
use Mtc\MercuryDataModels\VehicleTrim;

class ViewVehicleTrimRequest extends FormRequest
{
    private ?NewCar $carModel;
    private ?VehicleTrim $trimModel;

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize(): bool
    {
        if (is_null($this->getNewCar()) || is_null($this->getTrim())) {
            return false;
        }

        return $this->belongsToCar() && ($this->isActive() || $this->withAccessKey());
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        return [
            //
        ];
    }

    private function isActive(): bool
    {
        return (bool) $this->getTrim()?->active;
    }

    private function belongsToCar(): bool
    {
        return $this->getTrim()?->new_car_id === $this->getNewCar()?->id;
    }

    private function withAccessKey(): bool
    {
        return $this->input('a') === base64_encode($this->getTrim()?->id . '-' . $this->getTrim()?->slug);
    }

    public function getNewCar(): ?NewCar
    {
        if (!isset($this->carModel)) {
            $this->carModel = NewCar::query()
                ->where('slug', $this->car)
                ->first();
        }

        return $this->carModel;
    }

    public function getTrim(): ?VehicleTrim
    {
        if (!isset($this->trimModel)) {
            $this->trimModel = VehicleTrim::query()
                ->where('slug', $this->trim)
                ->first();
        }

        return $this->trimModel;
    }
}
