<?php

namespace App\Models;

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

class SimulationQuestion extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'interview_category_id',
        'question',
        'expected_keywords',
        'sample_answer',
        'points',
        'order',
    ];

    protected $casts = [
        'expected_keywords' => 'array',
        'points'            => 'integer',
        'order'             => 'integer',
    ];

    public function category(): BelongsTo
    {
        return $this->belongsTo(InterviewCategory::class, 'interview_category_id');
    }

    /**
     * Kullanıcının cevabını anahtar kelime eşleşmesiyle puanla
     * Maksimum puan: $this->points
     */
    public function scoreAnswer(string $answer): int
    {
        if (empty($this->expected_keywords) || empty(trim($answer))) {
            return 0;
        }

        $answerLower = mb_strtolower(trim($answer), 'UTF-8');
        $matched = 0;
        $total   = count($this->expected_keywords);

        foreach ($this->expected_keywords as $keyword) {
            $kw = mb_strtolower(trim($keyword), 'UTF-8');
            if ($kw !== '' && mb_strpos($answerLower, $kw) !== false) {
                $matched++;
            }
        }

        // Bonus: cevap yeterince uzunsa (%10 bonus)
        $ratio    = $total > 0 ? ($matched / $total) : 0;
        $score    = (int) round($this->points * $ratio);

        // Cevap 50 karakterden uzunsa minimum %10 puan garanti
        $minScore = strlen($answer) >= 50 ? (int) round($this->points * 0.1) : 0;

        return min($this->points, max($minScore, $score));
    }

    public function scopeByCategory($query, int $categoryId)
    {
        return $query->where('interview_category_id', $categoryId);
    }

    public function scopeOrdered($query)
    {
        return $query->orderBy('order')->orderBy('id');
    }
}
