<?php

namespace App\Http\Requests;

use App\Support\CustomerLedgerReport;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class CustomerLedgerReportRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()?->can('customer-ledger.view') ?? false;
    }

    /**
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        return [
            'customer_id' => ['nullable', 'integer', 'exists:customers,id'],
            'date_from' => ['nullable', 'date'],
            'date_to' => ['nullable', 'date', 'after_or_equal:date_from'],
            'payment_group' => ['nullable', 'string', Rule::in(CustomerLedgerReport::paymentGroupValues())],
        ];
    }

    /**
     * @return array{
     *     customer_id: int|null,
     *     date_from: string|null,
     *     date_to: string|null,
     *     payment_group: string,
     * }
     */
    public function filters(): array
    {
        $validated = $this->validated();

        return [
            'customer_id' => isset($validated['customer_id']) ? (int) $validated['customer_id'] : null,
            'date_from' => $validated['date_from'] ?? null,
            'date_to' => $validated['date_to'] ?? null,
            'payment_group' => $validated['payment_group'] ?? CustomerLedgerReport::PAYMENT_GROUP_DATE,
        ];
    }
}
