<?php

namespace App\Models\Dialler;

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

/**
 * One interval an agent spent in a single presence status.
 *
 * The currently-open interval has a null ended_at; closing it stamps ended_at
 * and denormalises duration_seconds. See App\Services\Dialler\AgentStatusService.
 */
class AgentStatusHistory extends Model
{
    use BelongsToSolicitor;

    protected $fillable = [
        'solicitor_id',
        'agent_id',
        'status',
        'started_at',
        'ended_at',
        'duration_seconds',
        'communication_id',
        'source',
        'meta',
    ];

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

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

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

    /** Intervals that have not yet been closed (at most one per agent). */
    public function scopeOpen(Builder $query): Builder
    {
        return $query->whereNull('ended_at');
    }

    /** Live duration — open intervals are measured up to now(). */
    public function getDurationInSecondsAttribute(): int
    {
        return (int) ($this->ended_at ?? now())->diffInSeconds($this->started_at);
    }

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