<?php

namespace App\Http\Requests;

use App\Models\FactoryProduct;
use App\Models\Sale;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class ExchangeSalePacksRequest extends FormRequest
{
    public function authorize(): bool
    {
        $sale = $this->route('sale');

        return $sale instanceof Sale
            && ($this->user()?->can('sales.exchange') === true
                || $this->user()?->can('sales.return') === true);
    }

    /**
     * @return array<string, array<int, mixed>>
     */
    public function rules(): array
    {
        /** @var Sale|null $sale */
        $sale = $this->route('sale');

        return [
            'return_lines' => ['required', 'array', 'min:1'],
            'return_lines.*.sale_pack_ids' => ['required', 'array', 'min:1'],
            'return_lines.*.sale_pack_ids.*' => [
                'required',
                'integer',
                Rule::exists('sale_packs', 'id')->where(
                    fn ($query) => $query->where('sale_id', $sale?->id),
                ),
            ],
            'return_lines.*.return_weight' => ['required', 'numeric', 'gt:0'],
            'return_lines.*.weight_price' => ['required', 'numeric', 'min:0'],
            'replacement_lines' => ['required', 'array', 'min:1'],
            'replacement_lines.*.factory_product_id' => ['required', 'integer', Rule::exists(FactoryProduct::class, 'id')],
            'replacement_lines.*.quantity_mode' => ['nullable', 'string', Rule::in(['pack', 'weight'])],
            'replacement_lines.*.quantity' => ['required', 'integer', 'min:1'],
            'replacement_lines.*.total_weight' => ['required', 'numeric', 'gt:0'],
            'replacement_lines.*.weight_price' => ['required', 'numeric', 'min:0'],
            'replacement_lines.*.return_cotton' => ['nullable', 'numeric', 'gte:0'],
            'replacement_lines.*.cotton_price' => ['nullable', 'numeric', 'gte:0'],
            'notes' => ['nullable', 'string', 'max:2000'],
        ];
    }
}
