<?php

declare(strict_types=1);

namespace App\Http\Requests\Invoice;

use App\Models\Invoice;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class StoreInvoiceRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'project_id' => ['required', 'integer', 'exists:projects,id'],
            'user_id' => ['nullable', 'integer', 'exists:users,id'],
            'recipient_ids' => ['nullable', 'array'],
            'recipient_ids.*' => ['integer', 'exists:users,id'],
            'type' => ['required', Rule::in([Invoice::TYPE_INCOME, Invoice::TYPE_EXPENSE])],
            'title' => ['required', 'string', 'max:255'],
            'description' => ['nullable', 'string'],
            'issued_at' => ['nullable', 'date'],
            'due_at' => ['nullable', 'date', 'after_or_equal:issued_at'],
            'commission_percent' => ['nullable', 'numeric', 'min:0', 'max:100'],
            'tracking_code' => ['nullable', 'string', 'max:100'],
            'payment_method' => ['nullable', Rule::in([Invoice::PAYMENT_CASH, Invoice::PAYMENT_CHECK])],
            'counterparty_name' => ['nullable', 'string', 'max:255'],
            'counterparty_phone' => ['nullable', 'string', 'max:30'],
            'is_draft' => ['nullable', 'boolean'],
            'status' => ['nullable', Rule::in([Invoice::STATUS_DRAFT, Invoice::STATUS_PENDING])],
            'meta' => ['nullable', 'array'],
            'meta.transport' => ['nullable', 'array'],
            'meta.transport.enabled' => ['nullable', 'boolean'],
            'meta.transport.amount' => ['nullable', 'integer', 'min:0'],
            'meta.transport.origin' => ['nullable', 'string', 'max:500'],
            'meta.transport.destination' => ['nullable', 'string', 'max:500'],
            'meta.transport.attachments' => ['nullable', 'array'],
            'meta.category' => ['nullable', 'string', 'max:100'],
            'meta.subcategory' => ['nullable', 'string', 'max:100'],
            'meta.attachments' => ['nullable', 'array'],
            'items' => ['required', 'array', 'min:1'],
            'items.*.name' => ['required', 'string', 'max:255'],
            'items.*.category' => ['nullable', 'string', 'max:100'],
            'items.*.subcategory' => ['nullable', 'string', 'max:100'],
            'items.*.quantity' => ['nullable', 'numeric', 'min:0'],
            'items.*.unit' => ['nullable', 'string', 'max:50'],
            'items.*.unit_price' => ['nullable', 'integer', 'min:0'],
            'items.*.total' => ['nullable', 'integer', 'min:0'],
            'items.*.description' => ['nullable', 'string'],
            'items.*.attachments' => ['nullable', 'array'],
        ];
    }
}
