<?php

namespace App\Http\Requests;

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

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

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

    /**
     * @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.*.return_condition' => [
                'required',
                'string',
                Rule::in(SaleReturnCondition::values()),
            ],
            'return_lines.*.return_amount' => ['nullable', 'numeric', 'gte:0'],
            'notes' => ['nullable', 'string', 'max:2000'],
        ];
    }
}
