<?php

namespace App\Http\Requests;

use App\Facades\Settings;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Http\FormRequest;
use Mtc\MercuryDataModels\Country;
use Mtc\MercuryDataModels\Vehicle;

class AutosOnShowNotificationRequest extends FormRequest
{
    protected ?Model $vehicle = null;

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return $this->header('authorization') === 'Bearer '
            . config('services.image-sync.autos-on-show.notification_token');
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'vehicleId' => [
                'required',
            ],
        ];
    }

    /**
     * Get the VRM in format of "AB69 DEF"
     *
     * @return string
     */
    public function vrm(): string
    {
        $vrm = str_replace(' ', '', $this->input('vehicleId'));
        return substr($vrm, 0, 4) . ' ' . substr($vrm, 4);
    }

    /**
     * Get the vehicle record
     *
     * @return Vehicle|Model|null
     */
    public function vehicle(): ?Vehicle
    {
        if (!isset($this->vehicle)) {
            $country = Settings::get('app-details-country') ?? config('app.default_country');
            $this->vehicle = Vehicle::query()
                ->where('registration_number', Country::normalizeNumberPlate($country, $this->input('vehicleId')))
                ->orWhere('vin', $this->input('vehicleId'))
                ->first();
        }

        return $this->vehicle;
    }
}
