<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Assessment extends Model
{
    protected $guarded = [];

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

    public function questions(): HasMany
    {
        return $this->hasMany(AssessmentQuestion::class)
            ->where('is_active', true)
            ->orderBy('sort');
    }

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

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

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

    public function overallBandFor(float $percent): ?AssessmentBand
    {
        return $this->bands
            ->whereNull('dimension')
            ->first(fn ($band) => $percent >= $band->min_percent && $percent <= $band->max_percent);
    }

    /** Band for a profile-mode result: the band whose dimension matches the dominant type. */
    public function profileBandFor(string $type): ?AssessmentBand
    {
        return $this->bands->firstWhere('dimension', $type);
    }

    public function isProfileMode(): bool
    {
        return ($this->settings['mode'] ?? null) === 'profile';
    }

    /** @return array<string, string> type key => human label (profile mode) */
    public function profileTypes(): array
    {
        return $this->settings['types'] ?? [];
    }

    public function getRouteKeyName(): string
    {
        return 'slug';
    }
}
