<?php

namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;

class StoreProductRequest extends FormRequest
{
    public function authorize(): bool
    {
        return auth()->user()->can('products.create') || auth()->user()->isAdmin();
    }

    public function rules(): array
    {
        return [
            'category_id' => 'required|exists:categories,id',
            'name' => ['required', 'string', $this->maxLengthRule(255), 'regex:/^[a-zA-Z0-9\s\-_.,()]+$/'],
            'tags' => ['nullable', 'string', $this->maxLengthRule(500), 'regex:/^[a-zA-Z0-9\s,.-]+$/'],
            'barcode' => ['nullable', 'string', $this->maxLengthRule(100), 'unique:products,barcode', 'regex:/^[a-zA-Z0-9]+$/'],
            'price' => ['required', 'numeric', $this->decimalRangeRule(0, 999999.99)],
            'mrp' => ['nullable', 'numeric', $this->decimalRangeRule(0, 999999.99), $this->mrpGtePriceRule()],
            'opening_stock' => ['required', 'integer', $this->integerRangeRule(0, 999999)],
            'unit_id' => 'nullable|exists:units,id',
            'short_desc' => ['nullable', 'string', $this->maxLengthRule(500), 'regex:/^[a-zA-Z0-9\s\-_.,()!?]+$/'],
            'long_desc' => ['nullable', 'string', $this->maxLengthRule(5000)],
            'image' => ['nullable', 'image', 'mimes:jpg,jpeg,png,webp', $this->maxFileKilobytesRule(5120), 'dimensions:min_width=100,min_height=100,max_width=2000,max_height=2000'],
            'is_active' => 'nullable|boolean',
            'is_featured' => 'nullable|boolean',
            'is_prebooking' => 'nullable|boolean',
        ];
    }

    public function messages(): array
    {
        return [
            'name.regex' => 'Product name contains invalid characters.',
            'tags.regex' => 'Tags can only contain letters, numbers, spaces, commas, periods, and hyphens.',
            'barcode.regex' => 'Barcode can only contain letters and numbers.',
            'mrp.gte' => 'MRP must be greater than or equal to the selling price.',
            'short_desc.regex' => 'Short description contains invalid characters.',
            'image.dimensions' => 'Image must be between 100x100 and 2000x2000 pixels.',
        ];
    }

    private function decimalRangeRule(float $min, float $max): \Closure
    {
        return static function (string $attribute, mixed $value, \Closure $fail) use ($min, $max): void {
            if ($value === null || $value === '') {
                return;
            }

            if (!is_numeric($value)) {
                return;
            }

            $number = (float) $value;
            if ($number < $min || $number > $max) {
                $fail("The {$attribute} must be between {$min} and {$max}.");
            }
        };
    }

    private function integerRangeRule(int $min, int $max): \Closure
    {
        return static function (string $attribute, mixed $value, \Closure $fail) use ($min, $max): void {
            if ($value === null || $value === '') {
                return;
            }

            if (filter_var($value, FILTER_VALIDATE_INT) === false) {
                return;
            }

            $number = (int) $value;
            if ($number < $min || $number > $max) {
                $fail("The {$attribute} must be between {$min} and {$max}.");
            }
        };
    }

    private function mrpGtePriceRule(): \Closure
    {
        return function (string $attribute, mixed $value, \Closure $fail): void {
            if ($value === null || $value === '') {
                return;
            }

            $price = $this->input('price');
            if (!is_numeric($value) || !is_numeric($price)) {
                return;
            }

            if ((float) $value < (float) $price) {
                $fail('MRP must be greater than or equal to the selling price.');
            }
        };
    }

    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 maxFileKilobytesRule(int $maxKb): \Closure
    {
        return static function (string $attribute, mixed $value, \Closure $fail) use ($maxKb): void {
            if (!$value instanceof \Illuminate\Http\UploadedFile) {
                return;
            }

            if (($value->getSize() ?: 0) > ($maxKb * 1024)) {
                $fail("The {$attribute} field must not exceed {$maxKb} KB.");
            }
        };
    }
}
