<?php

namespace App\Http\Requests;

use App\Enums\ChargeBasis;
use App\Http\Requests\Concerns\ValidatesDocumentSpaces;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class StoreInvoiceRequest extends FormRequest
{
    use ValidatesDocumentSpaces;

    public function authorize(): bool
    {
        return true;
    }

    /**
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        $bookingRequired = ! $this->filled('booking_id');

        return array_merge([
            'customer_id' => ['required', 'exists:customers,id'],
            'booking_id' => ['nullable', 'exists:bookings,id'],
            'quotation_id' => ['nullable', 'exists:quotations,id'],
            'invoice_date' => ['nullable', 'date'],
            'due_date' => ['nullable', 'date', 'after_or_equal:invoice_date'],
            'guest_count' => ['nullable', 'integer', 'min:0'],
            'currency' => ['nullable', 'string', 'size:3'],
            'payment_terms' => ['nullable', 'string', 'max:255'],
            'notes' => ['nullable', 'string'],
            'terms_and_conditions' => ['nullable', 'string'],
            'items' => ['nullable', 'array'],
            'items.*.description' => ['required_with:items', 'string', 'max:500'],
            'items.*.quantity' => ['nullable', 'numeric', 'min:0'],
            'items.*.unit_price' => ['nullable', 'numeric', 'min:0'],
            'items.*.charge_basis' => ['required_with:items', Rule::enum(ChargeBasis::class)],
            'items.*.guest_count' => ['nullable', 'integer', 'min:0'],
            'items.*.billable_days' => ['nullable', 'integer', 'min:1'],
            'items.*.billable_hours' => ['nullable', 'numeric', 'min:0'],
            'items.*.discount_amount' => ['nullable', 'numeric', 'min:0'],
            'items.*.tax_rate' => ['nullable', 'numeric', 'min:0'],
            'items.*.product_id' => ['nullable', 'exists:products,id'],
            'items.*.package_id' => ['nullable', 'exists:packages,id'],
        ], $this->documentBookingFieldRules(), $this->documentSpaceRules($bookingRequired));
    }
}
