<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class PreQuestion extends Model
{
    use HasFactory;

    protected $fillable = [
        'candidate_id',
        'import_id',
        'sequence',
        'index',
        'raw_markdown',
        'stem',
        'options',
        'images',
        'tables',
        'source',
    ];

    protected $casts = [
        'candidate_id' => 'integer',
        'sequence' => 'integer',
        'index' => 'integer',
        'options' => 'array',
        'images' => 'array',
        'tables' => 'array',
        'source' => 'array',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    public function import(): BelongsTo
    {
        return $this->belongsTo(MarkdownImport::class, 'import_id');
    }

    public function getFirstImageAttribute(): ?string
    {
        if (empty($this->images)) {
            return null;
        }

        $images = is_string($this->images) ? json_decode($this->images, true) : $this->images;
        return $images[0] ?? null;
    }

    public function getSourceListAttribute(): string
    {
        if (empty($this->source)) {
            return 'No source';
        }

        $source = is_string($this->source) ? json_decode($this->source, true) : $this->source;
        return implode(', ', $source);
    }

    public function getStemPreviewAttribute(): string
    {
        return \Str::limit($this->stem, 100);
    }
}
