<?php

namespace OtomaticAi\Traits;

use OtomaticAi\Modules\Module;
use OtomaticAi\Vendors\Carbon\Carbon;
use OtomaticAi\Vendors\Illuminate\Support\Arr;

trait HasLogs
{
    public function clearLogs()
    {
        $this->logs = null;
        $this->saveQuietly();
    }

    public function getLogsAttribute()
    {
        $modulesSlugs = Arr::map(Module::getList(), function ($module) {
            return $module::SLUG_NAME;
        });

        $logs = json_decode($this->attributes["logs"] ?? "[]", true);

        foreach ($logs as $index => $log) {
            if (empty($log["group"]) || !in_array($log["group"], $modulesSlugs)) {
                $logs[$index]["group"] = "_default";
            }
        }

        return $logs;
    }

    public function addLog($message, $group = "_default", $type = "info", $extras = null)
    {
        $logs = $this->logs;
        if (!is_array($logs)) {
            $logs = [];
        }

        $logs[] = [
            "group" => $group,
            "type" => $type,
            "message" => $message,
            "extras" => $extras,
            "created_at" => Carbon::now()
        ];
        $this->logs = $logs;
        $this->saveQuietly();
    }
}
