<?php

namespace App\Models;

use App\Models\Concerns\BelongsToOwner;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class AssessmentAnswer extends Model
{
    use BelongsToOwner;

    protected $table = 'care_assessment_answers';

    protected $fillable = [
        'owner_ref', 'assessment_id', 'question_id',
        'value_text', 'value_number', 'value_boolean', 'value_date', 'value_json',
    ];

    protected function casts(): array
    {
        return [
            'value_number' => 'decimal:4',
            'value_boolean' => 'boolean',
            'value_date' => 'datetime',
            'value_json' => 'array',
        ];
    }

    public function assessment(): BelongsTo
    {
        return $this->belongsTo(Assessment::class, 'assessment_id');
    }

    public function question(): BelongsTo
    {
        return $this->belongsTo(AssessmentQuestion::class, 'question_id');
    }

    /**
     * Authoritative value for the given answer type (unused columns must stay null at write time).
     */
    public function authoritativeValue(?string $answerType = null): mixed
    {
        $type = $answerType ?? $this->question?->answer_type;

        return match ($type) {
            AssessmentQuestion::TYPE_TEXT,
            AssessmentQuestion::TYPE_TEXTAREA,
            AssessmentQuestion::TYPE_SINGLE_CHOICE => $this->value_text,
            AssessmentQuestion::TYPE_NUMBER,
            AssessmentQuestion::TYPE_INTEGER,
            AssessmentQuestion::TYPE_SCALE,
            AssessmentQuestion::TYPE_SCORE_ITEM,
            AssessmentQuestion::TYPE_CALCULATED => $this->value_number,
            AssessmentQuestion::TYPE_BOOLEAN => $this->value_boolean,
            AssessmentQuestion::TYPE_DATE,
            AssessmentQuestion::TYPE_DATETIME => $this->value_date,
            AssessmentQuestion::TYPE_MULTI_CHOICE => $this->value_json,
            default => $this->value_text ?? $this->value_number ?? $this->value_boolean ?? $this->value_date ?? $this->value_json,
        };
    }
}
