<?php

namespace App\Models\Claim;

use App\Models\User\User;
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 = [
        'status_id',
        'started_at',
        'ended_at',
        'changed_by',
    ];

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


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

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

    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);
    }
}
