<?php

namespace App\Http\Requests;

use App\Models\PlatformInstance;
use App\Services\Platform\CommunityDirectory;
use Exception;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

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

    /**
     * @return array<string, array<int, mixed>|string>
     */
    public function rules(): array
    {
        try {
            $communityRules = [
                Rule::in($this->communityIds()),
                Rule::unique('platform_channels', 'channel_id')
                    ->where('platform_instance_id', $this->input('platform_instance_id')),
            ];
        } catch (Exception $e) {
            // Falling through to Rule::in([]) would report the community as non-existent
            // when the truth is we never reached the instance to check.
            $message = 'Could not reach this instance to list its communities: '.$e->getMessage();
            $communityRules = [fn ($attribute, $value, $fail) => $fail($message)];
        }

        return [
            'platform_instance_id' => 'required|exists:platform_instances,id',
            'channel_id' => ['required', 'integer', ...$communityRules],
            'language_id' => 'nullable|exists:languages,id',
            'description' => 'nullable|string',
        ];
    }

    /**
     * @return array<string, string>
     */
    public function messages(): array
    {
        return [
            'channel_id.in' => 'That community does not exist on the selected instance.',
            'channel_id.unique' => 'A channel for this community already exists.',
        ];
    }

    /**
     * @return array<int, int>
     */
    private function communityIds(): array
    {
        $instance = PlatformInstance::query()->find((int) $this->input('platform_instance_id'));

        if (! $instance) {
            return [];
        }

        return collect(app(CommunityDirectory::class)->forInstance($instance))
            ->pluck('id')
            ->all();
    }
}
