<?php

declare(strict_types=1);

namespace App\Http\Requests\Collections;

use App\Models\Collection;
use Illuminate\Foundation\Http\FormRequest;

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

    public function rules(): array
    {
        return [
            'target_collection_id' => ['required', 'integer', 'exists:collections,id'],
        ];
    }

    public function withValidator($validator): void
    {
        $validator->after(function ($validator): void {
            $targetCollectionId = (int) $this->input('target_collection_id');
            $collection = $this->route('collection');

            if ($collection instanceof Collection && $targetCollectionId === (int) $collection->id) {
                $validator->errors()->add('target_collection_id', 'Choose a different target collection.');
            }
        });
    }
}