<?php

declare(strict_types=1);

namespace App\Http\Requests\Report;

use App\Models\Report;
use App\Models\ReportRationWeekly;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;

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

    public function rules(): array
    {
        $isDraft = $this->boolean('is_draft') || $this->input('status') === 'draft';

        return [
            'is_draft' => ['nullable', 'boolean'],
            'create_invoice' => ['nullable', 'boolean'],
            'project_id' => [$isDraft ? 'nullable' : 'required', 'integer', 'exists:projects,id'],
            'producer_id' => ['nullable', 'integer', 'exists:producers,id'],
            'product_id' => ['nullable', 'integer', 'exists:products,id'],
            'user_id' => ['nullable', 'integer', 'exists:users,id'],
            'title' => ['nullable', 'string', 'max:255'],
            'date' => ['required', 'date'],
            'report_at' => ['nullable', 'date'],
            'ration_type' => ['nullable', 'string', 'max:100'],
            'desc' => ['nullable', 'string'],
            'written_report' => ['nullable', 'string'],
            'warnings' => ['nullable', 'string'],
            'water_temp' => ['nullable', 'numeric'],
            'water_per_unit_daily' => ['nullable', 'numeric', 'min:0'],
            'wait_between_meals_hours' => ['nullable', 'numeric', 'min:0'],
            'mix_type' => ['nullable', 'string', Rule::in(array_keys(Report::mixTypeOptions()))],
            'status' => ['nullable', 'in:draft,published,archived'],
            'attachments' => ['nullable', 'array'],
            'attachments.*' => ['string', 'max:500'],
            'documents' => ['nullable', 'array'],
            'documents.*' => ['string', 'max:500'],
            'items' => [$isDraft ? 'nullable' : 'required', 'array', 'min:1'],
            'items.*.product_id' => ['required_with:items', 'integer', 'exists:products,id'],
            'items.*.group_name' => ['nullable', 'string', 'max:120'],
            'ration_ingredients' => ['nullable', 'array'],
            'ration_ingredients.*.name' => ['required_with:ration_ingredients', 'string', 'max:255'],
            'ration_ingredients.*.unit' => ['nullable', 'string', 'max:50'],
            'ration_ingredients.*.quantity_per_unit' => ['nullable', 'numeric', 'min:0'],
            'ration_ingredients.*.price_per_unit' => ['nullable', 'numeric', 'min:0'],
            'feeding_meals' => ['nullable', 'array'],
            'feeding_meals.*.meal_time' => ['nullable', 'string', 'max:20'],
            'feeding_meals.*.name' => ['nullable', 'string', 'max:255'],
            'feeding_meals.*.percent_of_total' => ['nullable', 'numeric', 'min:0', 'max:100'],
            'ration_weekly' => ['nullable', 'array'],
            'ration_weekly.*.day_of_week' => ['required_with:ration_weekly', 'integer', 'min:1', 'max:7'],
            'ration_weekly.*.is_active' => ['nullable', 'boolean'],
            'ration_weekly.*.status' => ['nullable', 'string', Rule::in(array_keys(ReportRationWeekly::statusOptions()))],
        ];
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator): void {
            $items = $this->input('items', []);
            if (! is_array($items) || $items === []) {
                return;
            }

            $productIds = collect($items)->pluck('product_id')->filter()->map(fn ($id) => (int) $id);
            if ($productIds->count() !== $productIds->unique()->count()) {
                $validator->errors()->add(
                    'items',
                    'هر محصول فقط می‌تواند در یک گروه مصرف‌کننده باشد.'
                );
            }
        });
    }

    public function messages(): array
    {
        return [
            'project_id.required' => 'انتخاب پروژه الزامی است.',
            'date.required' => 'تاریخ جیره الزامی است.',
            'items.required' => 'انتخاب حداقل یک محصول در گروه مصرف‌کننده الزامی است.',
        ];
    }
}
