<?php

namespace App\Models\Witness;

use App\Interface\NoteOwner;
use App\Models\Claim\Claim;
use App\Models\Client\Client;
use App\Trait\BelongsToSolicitor;
use App\Trait\HasNotes;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * A witness-statement workspace attached to a claim. Holds the answers,
 * exhibits, internal notes and immutable generated versions. The questionnaire
 * structure itself lives in config (see App\Support\Witness\WitnessQuestionnaire).
 */
class WitnessStatement extends Model implements NoteOwner
{
    use BelongsToSolicitor, HasFactory, HasNotes, SoftDeletes;

    protected $fillable = [
        'solicitor_id',
        'client_id',
        'claim_id',
        'status',
        'generation_options',
        'current_version_id',
    ];

    protected $casts = [
        'generation_options' => 'array',
    ];

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

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

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

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

    public function versions(): HasMany
    {
        return $this->hasMany(WitnessStatementVersion::class)->orderByDesc('version_number');
    }

    public function currentVersion(): BelongsTo
    {
        return $this->belongsTo(WitnessStatementVersion::class, 'current_version_id');
    }

    public function isGenerated(): bool
    {
        return in_array($this->status, ['generated', 'approved'], true);
    }

    public function isApproved(): bool
    {
        return $this->status === 'approved';
    }
}
