<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Log;
use Mtc\MercuryDataModels\VehicleOffer;

class ViewOfferRequest extends FormRequest
{
    private ?VehicleOffer $model = null;

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        if (is_null($this->getOffer())) {
            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->getOffer()?->published ?? false;
    }

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

    public function getOffer(): ?VehicleOffer
    {
        if (!isset($this->model)) {
            $this->model = VehicleOffer::query()->where('slug', $this->offer)->first();
        }

        return $this->model;
    }
}
