<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

final class Question extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'question_bank_id',
        'category_id',
        'creator_id',
        'type',
        'content',
        'explanation',
        'answers',
        'source_question_id',
        'dedup_hash',
        'is_active',
    ];

    protected $casts = [
        'answers' => 'array',
        'is_active' => 'boolean',
    ];

    public function bank(): BelongsTo
    {
        return $this->belongsTo(QuestionBank::class, 'question_bank_id');
    }

    public function options(): HasMany
    {
        return $this->hasMany(QuestionOption::class)->orderBy('sort');
    }

    public function tags(): BelongsToMany
    {
        return $this->belongsToMany(QuestionTag::class, 'question_tag');
    }

    public function wrongQuestions(): HasMany
    {
        return $this->hasMany(WrongQuestion::class);
    }

    public function correctOptionIds(): array
    {
        return $this->options->where('is_correct', true)->pluck('id')->map(fn ($id) => (int) $id)->values()->all();
    }
}
