<?php

namespace App\Http\Requests;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Support\Facades\Auth;

/**
 * Base Form Request
 *
 * Provides common functionality for all form requests including
 * standardized error responses and authorization checks.
 */
abstract class BaseFormRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return Auth::check();
    }

    /**
     * Get custom attributes for validator errors.
     */
    public function attributes(): array
    {
        return [];
    }

    /**
     * Get custom messages for validator errors.
     */
    public function messages(): array
    {
        return [];
    }

    /**
     * Handle a failed validation attempt.
     */
    protected function failedValidation(Validator $validator): void
    {
        if ($this->expectsJson()) {
            throw new HttpResponseException(
                response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors(),
                ], 422)
            );
        }

        parent::failedValidation($validator);
    }

    /**
     * Prepare the data for validation.
     */
    protected function prepareForValidation(): void
    {
        // Override in child classes if needed
    }

    /**
     * Get validated data with defaults
     */
    public function validatedWithDefaults(array $defaults = []): array
    {
        return array_merge($defaults, $this->validated());
    }

    /**
     * Check if current user has specific role
     */
    protected function hasRole(string $role): bool
    {
        return Auth::user()?->role === $role;
    }

    /**
     * Check if user is SuperAdmin
     */
    protected function isSuperAdmin(): bool
    {
        return $this->hasRole('superadmin');
    }
}
