<?php

namespace App\Http\Requests;

use App\Support\DoughUsageReport;
use Illuminate\Foundation\Http\FormRequest;

class DoughUsageReportRequest extends FormRequest
{
    public function authorize(): bool
    {
        return (bool) $this->user()?->can('dough-usage.view');
    }

    /**
     * @return array<string, array<int, mixed>>
     */
    public function rules(): array
    {
        return [
            'date_from' => ['nullable', 'date'],
            'date_to' => ['nullable', 'date', 'after_or_equal:date_from'],
            'factory_product_id' => ['nullable', 'integer'],
            'quick_range' => ['nullable', 'string', 'in:today,this_week,this_month,this_year'],
        ];
    }

    /**
     * @return array<string, string|null>
     */
    public function filters(): array
    {
        $quickRange = $this->string('quick_range')->toString() ?: null;
        $now = now();

        if ($quickRange) {
            return match ($quickRange) {
                'today' => [
                    'date_from' => $now->toDateString(),
                    'date_to' => $now->toDateString(),
                    'factory_product_id' => $this->input('factory_product_id') ?: null,
                ],
                'this_week' => [
                    'date_from' => $now->copy()->startOfWeek()->toDateString(),
                    'date_to' => $now->copy()->endOfWeek()->toDateString(),
                    'factory_product_id' => $this->input('factory_product_id') ?: null,
                ],
                'this_year' => [
                    'date_from' => $now->copy()->startOfYear()->toDateString(),
                    'date_to' => $now->copy()->endOfYear()->toDateString(),
                    'factory_product_id' => $this->input('factory_product_id') ?: null,
                ],
                default => [
                    'date_from' => $now->copy()->startOfMonth()->toDateString(),
                    'date_to' => $now->toDateString(),
                    'factory_product_id' => $this->input('factory_product_id') ?: null,
                ],
            };
        }

        $defaults = DoughUsageReport::defaultFilters();

        return [
            'date_from' => $this->input('date_from', $defaults['date_from']),
            'date_to' => $this->input('date_to', $defaults['date_to']),
            'factory_product_id' => $this->input('factory_product_id') ?: null,
        ];
    }
}
