<?php

namespace App\Http\Requests;

use App\Models\Customer;
use App\Models\FactoryProduct;
use App\Support\CashSaleCustomer;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class StoreCustomerOrderRequest extends FormRequest
{
    public function authorize(): bool
    {
        return (bool) $this->user()?->can('customer-orders.create');
    }

    /**
     * @return array<string, array<int, mixed>>
     */
    public function rules(): array
    {
        return [
            'customer_id' => [
                'required',
                'integer',
                Rule::exists(Customer::class, 'id')->where('is_active', true),
                function (string $attribute, mixed $value, \Closure $fail): void {
                    if (CashSaleCustomer::isCashCustomer((int) $value)) {
                        $fail(__('Cash customer cannot place orders.'));
                    }
                },
            ],
            'ordered_at' => ['required', 'date'],
            'notes' => ['nullable', 'string', 'max:2000'],
            'items' => ['required', 'array', 'min:1'],
            'items.*.factory_product_id' => [
                'required',
                'integer',
                Rule::exists(FactoryProduct::class, 'id')->where('is_active', true),
            ],
            'items.*.quantity' => ['required', 'numeric', 'gt:0'],
        ];
    }
}
