<?php

namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;

class UpdateCouponRequest extends FormRequest
{
    public function authorize(): bool
    {
        return auth()->user()->can('coupons.update') || auth()->user()->isAdmin();
    }

    public function rules(): array
    {
        return [
            'code' => ['required', 'string', $this->maxLengthRule(50), 'unique:coupons,code,' . $this->coupon->id],
            'type' => 'required|in:percentage,flat',
            'value' => ['required', 'numeric', $this->decimalMinRule(0)],
            'min_cart_value' => ['nullable', 'numeric', $this->decimalMinRule(0)],
            'max_discount' => ['nullable', 'numeric', $this->decimalMinRule(0)],
            'starts_at' => 'required|date',
            'ends_at' => 'required|date|after:starts_at',
            'usage_limit' => ['nullable', 'integer', $this->integerMinRule(1)],
            'usage_per_user' => ['nullable', 'integer', $this->integerMinRule(1)],
            'is_active' => 'nullable|boolean',
        ];
    }

    private function maxLengthRule(int $max): \Closure
    {
        return static function (string $attribute, mixed $value, \Closure $fail) use ($max): void {
            if (is_string($value) && mb_strlen($value) > $max) {
                $fail("The {$attribute} field must not exceed {$max} characters.");
            }
        };
    }

    private function decimalMinRule(float $min): \Closure
    {
        return static function (string $attribute, mixed $value, \Closure $fail) use ($min): void {
            if ($value === null || $value === '' || !is_numeric($value)) {
                return;
            }

            if ((float) $value < $min) {
                $fail("The {$attribute} must be at least {$min}.");
            }
        };
    }

    private function integerMinRule(int $min): \Closure
    {
        return static function (string $attribute, mixed $value, \Closure $fail) use ($min): void {
            if ($value === null || $value === '' || filter_var($value, FILTER_VALIDATE_INT) === false) {
                return;
            }

            if ((int) $value < $min) {
                $fail("The {$attribute} must be at least {$min}.");
            }
        };
    }
}
