<?php

declare(strict_types=1);

namespace App\Http\Requests\Collections;

use Illuminate\Foundation\Http\FormRequest;

class UpdateCollectionSeriesRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user() !== null;
    }

    protected function prepareForValidation(): void
    {
        foreach (['series_key', 'series_title', 'series_description'] as $field) {
            if ($this->has($field) && trim((string) $this->input($field)) === '') {
                $this->merge([$field => null]);
            }
        }

        if ($this->has('series_order') && trim((string) $this->input('series_order')) === '') {
            $this->merge(['series_order' => null]);
        }
    }

    public function rules(): array
    {
        return [
            'series_key' => ['nullable', 'string', 'max:80'],
            'series_title' => ['nullable', 'string', 'max:160'],
            'series_description' => ['nullable', 'string', 'max:400'],
            'series_order' => ['nullable', 'integer', 'min:1', 'max:9999'],
        ];
    }

    public function withValidator($validator): void
    {
        $validator->after(function ($validator): void {
            $seriesKey = $this->input('series_key');
            $seriesTitle = $this->input('series_title');
            $seriesDescription = $this->input('series_description');
            $seriesOrder = $this->input('series_order');

            $hasSeriesMetadata = filled($seriesTitle) || filled($seriesDescription) || filled($seriesOrder);

            if ($hasSeriesMetadata && blank($seriesKey)) {
                $validator->errors()->add('series_key', 'Series key is required when series metadata is provided.');
            }
        });
    }
}
