<?php

namespace App\Trait;

use App\Actions\Communications\EvaluateContactTriggersAction;
use App\Enum\Contact\TemplateTriggerType;
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
    {
        $previousStatusId = $this->currentStatusHistory()?->status_id;

        // 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(),
        ]);

        // Fire automatic contact triggers matching this status transition.
        try {
            app(EvaluateContactTriggersAction::class)(
                $this,
                TemplateTriggerType::STATUS_CHANGED,
                [
                    'from_status_id' => $previousStatusId,
                    'to_status_id' => $newStatusId,
                ],
            );
        } catch (\Throwable $e) {
            logger()->error('Contact trigger evaluation failed on status change', [
                'subject' => static::class,
                'subject_id' => $this->getKey(),
                'error' => $e->getMessage(),
            ]);
        }
    }


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