<?php

/** @noinspection PhpUnhandledExceptionInspection */

/** @noinspection PhpUnused */

namespace DefStudio\GameEngine\Decorators\Tasks;

use Illuminate\Support\Str;
use DefStudio\GameEngine\Attributes\CallableFromLivewire;

class MultipleChoiceQuestion extends TaskDecorator
{
    public static function type_label(): string
    {
        return __('Multiple Choice Question');
    }

    public static function configuration_component(): string
    {
        return 'game-engine::tasks.multiple-choice-question.configuration';
    }

    public static function run_component(): string
    {
        return 'game-engine::tasks.multiple-choice-question.run';
    }

    public function question(): string
    {
        return $this->configuration['question'] ?? '';
    }

    public function answers(): array
    {
        return $this->configuration['answers'] ?? [];
    }

    public function should_randomize_answers_order(): bool
    {
        return $this->configuration['randomize_answers_order'] ?? false;
    }

    #[CallableFromLivewire()]
    public function add_answer(): self
    {
        $this->configuration['answers'][] = [
            'id' => Str::uuid(),
            'answer' => '',
            'correct' => false,
        ];

        return $this;
    }

    #[CallableFromLivewire()]
    public function delete_answer(int $index): self
    {
        unset($this->configuration['answers'][$index]);

        return $this;
    }

    public function is_complete(array $state): bool
    {
        return !empty($state['answer']);
    }

    protected function get_answer(string $id): array
    {
        $answer = collect($this->answers())->first(fn(array $answer) => $answer['id'] === $id);

        throw_if($answer === null, 'Invalid answer ID');

        return $answer;
    }
}
