<?php

namespace App\Http\Requests\Admin\Banner\Concerns;

use App\Models\Academy;
use App\Models\Banner;
use App\Models\Championship;
use App\Models\Game;
use App\Models\News;
use Illuminate\Validation\Rule;

trait ValidatesBannerLinkable
{
    protected function prepareLinkableForValidation(): void
    {
        $type = $this->input('linkable_type');
        if ($type === null || $type === '' || $type === 'none') {
            $this->merge([
                'linkable_type' => null,
                'linkable_id' => null,
            ]);
        }
    }

    /**
     * @return array<string, mixed>
     */
    protected function linkableRules(): array
    {
        $allowed = Banner::linkableTypeClasses();
        $type = $this->input('linkable_type');

        $idRules = ['nullable', 'integer'];
        if (is_string($type) && $type !== '' && in_array($type, $allowed, true)) {
            $table = match ($type) {
                Game::class => 'games',
                Championship::class => 'championships',
                News::class => 'news',
                Academy::class => 'academies',
                default => null,
            };
            if ($table !== null) {
                $idRules = ['required', 'integer', Rule::exists($table, 'id')];
            }
        }

        return [
            'linkable_type' => ['nullable', 'string', Rule::in($allowed)],
            'linkable_id' => $idRules,
        ];
    }
}
