<?php

namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;

class UpdateProductRequest extends FormRequest
{
    public function authorize(): bool
    {
        return auth()->user()->can('products.update') || auth()->user()->isAdmin();
    }

    public function rules(): array
    {
        return [
            'category_id' => 'required|exists:categories,id',
            'name' => ['required', 'string', $this->maxLengthRule(255)],
            'tags' => ['nullable', 'string', $this->maxLengthRule(500)],
            'barcode' => ['nullable', 'string', $this->maxLengthRule(100), 'unique:products,barcode,' . $this->product->id],
            'price' => ['required', 'numeric', $this->decimalMinRule(0)],
            'mrp' => ['nullable', 'numeric', $this->decimalMinRule(0)],
            // opening_stock is not editable after creation, so no validation needed
            'unit_id' => 'nullable|exists:units,id',
            'short_desc' => ['nullable', 'string', $this->maxLengthRule(500)],
            'long_desc' => 'nullable|string',
            'image' => ['nullable', 'image', 'mimes:jpg,jpeg,png,webp', $this->maxFileKilobytesRule(5120)],
            'is_active' => 'nullable|boolean',
            'is_featured' => 'nullable|boolean',
            'is_prebooking' => 'nullable|boolean',
        ];
    }

    private function decimalMinRule(float $min): \Closure
    {
        return static function (string $attribute, mixed $value, \Closure $fail) use ($min): void {
            if ($value === null || $value === '') {
                return;
            }

            if (!is_numeric($value)) {
                return;
            }

            if ((float) $value < $min) {
                $fail("The {$attribute} must be at least {$min}.");
            }
        };
    }

    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.");
            }
        };
    }
}
