<?php

namespace App\Http\Requests;

use App\Facades\Feature;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Validation\Rule;
use Mtc\MercuryDataModels\Enums\VehicleSubscriptionEventType;
use Mtc\MercuryDataModels\Vehicle;

class StoreVehicleSubscriptionRequest extends FormRequest
{
    public function authorize(): bool
    {
        if (!Feature::isEnabled('vehicle-subscriptions')) {
            return false;
        }

        $vehicle = $this->getVehicle();

        if (!$vehicle || $vehicle->is_sold || $vehicle->deleted_at) {
            return false;
        }

        return true;
    }

    protected function failedAuthorization(): void
    {
        if (!Feature::isEnabled('vehicle-subscriptions')) {
            throw new HttpResponseException(response()->json([
                'success' => false,
                'message' => __('vehicle_subscriptions.not_available'),
            ], 403));
        }

        throw new HttpResponseException(response()->json([
            'success' => false,
            'message' => __('vehicle_subscriptions.vehicle_not_available'),
        ], 400));
    }

    public function rules(): array
    {
        return [
            'email' => ['required', 'email', 'max:255'],
            'first_name' => ['nullable', 'string', 'max:255'],
            'last_name' => ['nullable', 'string', 'max:255'],
            'event_types' => ['required', 'array', 'min:1'],
            'event_types.*' => ['string', Rule::in(VehicleSubscriptionEventType::values())],
        ];
    }

    protected function failedValidation(Validator $validator): void
    {
        throw new HttpResponseException(response()->json([
            'success' => false,
            'message' => $validator->errors()->first(),
            'errors' => $validator->errors(),
        ], 422));
    }

    private function getVehicle(): ?Vehicle
    {
        return $this->route('vehicle');
    }
}
