<?php

namespace App\Http\Requests;

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

class ViewNewCarRequest extends FormRequest
{
    private ?NewCar $model = null;

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

        return $this->public() || $this->withAccessKey();
    }

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

    private function public(): bool
    {
        return $this->getNewCar()?->published ?? false;
    }

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

    public function getNewCar(): ?NewCar
    {
        if (!isset($this->model)) {
            $this->model = NewCar::query()
                ->where('slug', $this->car)
                ->when($this->filled('make_slug'), fn($query) => $query->whereHas(
                    'make',
                    fn($query) => $query->where('slug', $this->input('make_slug'))
                ))
                ->first();
        }

        return $this->model;
    }
}
