<?php

namespace App\Http\Requests\Api\V1\Parking;

use App\Http\Requests\Api\ApiFormRequest;
use App\Models\Member;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Validation\Rule;

class StoreParkingRequest extends ApiFormRequest
{
    public function rules(): array
    {
        $member = $this->user();

        return [
            'car_number' => [
                'required',
                'string',
                'max:50',
                Rule::unique('parkings', 'car_number')->where('member_id', $member?->id ?? 0),
            ],
            'make'  => ['nullable', 'string', 'max:100'],
            'model'  => ['nullable', 'string', 'max:100'],
            'color'  => ['nullable', 'string', 'max:50'],
        ];
    }

    public function messages(): array
    {
        return [
            'car_number.unique' => __('This car number is already registered.'),
        ];
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator) {
            $member = $this->user();
            if (! $member instanceof Member) {
                $validator->errors()->add('member', __('Invalid member.'));

                return;
            }
           
            if (! $member->hasActiveSubscription()) {
                $validator->errors()->add('subscription', __('Subscription must be active to add vehicles.'));
                return;
            }
            $count = $member->parkings()->count();
            if ($count >= 2) {
                $validator->errors()->add('parking', __('Maximum 2 vehicles allowed per member.'));
            }
        });
    }

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