<?php

namespace App\Http\Requests\Admin;

use App\Models\StockAdjustment;
use Illuminate\Foundation\Http\FormRequest;

class StoreManualAdjustmentRequest extends FormRequest
{
    public static function reasonOptions(): array
    {
        return [
            'Damaged' => 'Damaged',
            'Found' => 'Found',
            'Correction' => 'Correction',
            'Return' => 'Return',
            'Stock audit' => 'Stock audit',
            'Other' => 'Other',
        ];
    }

    public function authorize(): bool
    {
        return auth()->user()?->can('stock-adjustments.manage') ?? false;
    }

    public function rules(): array
    {
        $productId = $this->input('product_id');
        $product = $productId ? \App\Models\Product::find($productId) : null;
        $variantRequired = $product && $product->isVariantParent();

        return [
            'product_id' => ['required', 'exists:products,id'],
            'variant_id' => $variantRequired ? ['required', 'exists:products,id'] : ['nullable', 'exists:products,id'],
            'adjustment_type' => ['required', 'in:addition,subtraction'],
            'quantity' => ['required', 'numeric', 'min:0.01'],
            'reason' => ['required', 'string', 'in:' . implode(',', array_keys(self::reasonOptions()))],
            'remarks' => ['required', 'string', 'min:10'],
        ];
    }

    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            if ($this->adjustment_type === StockAdjustment::TYPE_SUBTRACTION) {
                $productId = $this->variant_id ?? $this->product_id;
                $product = \App\Models\Product::find($productId);
                if ($product && $product->current_stock < (float) $this->quantity) {
                    $validator->errors()->add('quantity', 'Subtraction cannot exceed current stock (' . $product->current_stock . ').');
                }
            }
        });
    }
}
