<?php

namespace App\Models\Claim;

use App\Models\User\User;
use App\Trait\BelongsToSolicitor;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;

class StatusHistory extends Model {
    protected $fillable = [
        'solicitor_id',
        'status_id',
        'started_at',
        'ended_at',
        'changed_by',
    ];

    protected $casts = [
        'started_at' => 'datetime',
        'ended_at' => 'datetime',
    ];

    use BelongsToSolicitor;

    public function subject(): MorphTo {
        return $this->morphTo();
    }

    public function status(): BelongsTo {
        // Keep historical references resolvable even after a status is soft-deleted.
        return $this->belongsTo(Status::class)->withTrashed();
    }

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

    public function getDurationInSecondsAttribute(): int {
        return ($this->ended_at ?? now())->diffInSeconds($this->started_at);
    }

    public function getDurationHumanAttribute(): string {
        return Carbon::parse($this->started_at)
            ->diffForHumans($this->ended_at ?? now(), true);
    }
}
