<?php

namespace App\Models\Witness;

use App\Models\User\User;
use App\Trait\BelongsToSolicitor;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * A single answer to a questionnaire question, with its provenance (where the
 * value came from) and review status (the lifecycle of a machine suggestion).
 *
 * Origins:  client_data | claim_data | evidence | user | previous
 * Statuses: manual | suggested | accepted | edited | rejected
 */
class WitnessStatementAnswer extends Model
{
    use BelongsToSolicitor, HasFactory;

    protected $fillable = [
        'solicitor_id',
        'witness_statement_id',
        'section_key',
        'question_key',
        'value',
        'origin',
        'review_status',
        'provenance',
        'answered_by',
    ];

    protected $casts = [
        'value' => 'array',
        'provenance' => 'array',
    ];

    public function witnessStatement(): BelongsTo
    {
        return $this->belongsTo(WitnessStatement::class);
    }

    public function answeredBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'answered_by');
    }

    public function scopeSuggested(Builder $query): void
    {
        $query->where('review_status', 'suggested');
    }

    public function scopeAwaitingReview(Builder $query): void
    {
        $query->where('review_status', 'suggested');
    }

    public function scopeByOrigin(Builder $query, string $origin): void
    {
        $query->where('origin', $origin);
    }

    public function isSuggested(): bool
    {
        return $this->review_status === 'suggested';
    }

    public function isFromEvidence(): bool
    {
        return $this->origin === 'evidence';
    }

    /**
     * A human-friendly label for where this answer came from.
     */
    public function originLabel(): string
    {
        return match ($this->origin) {
            'client_data' => 'Client record',
            'claim_data' => 'Claim record',
            'evidence' => 'Extracted evidence',
            'previous' => 'Previous answer',
            default => 'Manual entry',
        };
    }
}
