<?php

namespace App\Trait;

use App\Models\Claim\Status;
use App\Models\Claim\StatusHistory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphMany;

trait HasStatus {

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

    public function statusHistory(): MorphMany
    {
        return $this->morphMany(StatusHistory::class, 'subject')
            ->orderByDesc('started_at');
    }

    public function currentStatusHistory(): ?StatusHistory
    {
        return $this->statusHistory()
            ->whereNull('ended_at')
            ->latest('started_at')
            ->first();
    }

    public function updateStatus(int $newStatusId): void
    {
        // Close existing status
        $this->currentStatusHistory()
            ?->update([
                'ended_at' => now(),
            ]);

        // Start new status
        $this->statusHistory()->create([
            'status_id'  => $newStatusId,
            'started_at' => now(),
            'changed_by' => auth()->id(),
        ]);
    }


    public function timeSpentPerStatus(): array
    {
        return $this->statusHistory
            ->groupBy('status_id')
            ->map(fn ($entries) =>
            $entries->sum->duration_in_seconds
            )
            ->toArray();
    }

    public function totalTimeInCurrentStatus(): int
    {
        return $this->currentStatusHistory()
            ?->duration_in_seconds ?? 0;
    }
}