<?php

namespace App\Http\Requests;

use App\Models\ProductReview;
use Carbon\Carbon;
use Illuminate\Foundation\Http\FormRequest;

class UpdateReviewRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        $review = $this->route('review') ?? ProductReview::find($this->route('id'));

        if (!$review) {
            return false;
        }

        $user = auth()->user();

        // Admin can always update
        if ($user && ($user->isAdmin() || $user->isStaff())) {
            return true;
        }

        // Check if user is the author
        if (!$user || $review->user_id !== $user->id) {
            return false;
        }

        // Check if within edit time limit
        $editTimeLimit = config('reviews.edit_time_limit_hours', 24);
        $timeLimit = $review->created_at->addHours($editTimeLimit);

        if (now()->gt($timeLimit)) {
        return false;
        }

        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'rating' => 'required|integer|min:1|max:5',
            'title' => 'nullable|string|max:255',
            'body' => 'nullable|string|max:5000',
        ];
    }

    /**
     * Get custom messages for validator errors.
     */
    public function messages(): array
    {
        return [
            'rating.required' => 'Please select a rating.',
            'rating.integer' => 'Rating must be a number.',
            'rating.min' => 'Rating must be at least 1 star.',
            'rating.max' => 'Rating cannot exceed 5 stars.',
            'title.max' => 'Title cannot exceed 255 characters.',
            'body.max' => 'Review text cannot exceed 5000 characters.',
        ];
    }
}
