<?php

namespace App\Services\Log;

use App\Enums\LogLevelEnum;
use App\Models\Log;
use App\Models\PlatformChannel;

class LogSaver
{
    /**
     * @param  array<string, mixed>  $context
     */
    public function info(string $message, ?PlatformChannel $channel = null, array $context = []): void
    {
        $this->log(LogLevelEnum::INFO, $message, $channel, $context);
    }

    /**
     * @param  array<string, mixed>  $context
     */
    public function error(string $message, ?PlatformChannel $channel = null, array $context = []): void
    {
        $this->log(LogLevelEnum::ERROR, $message, $channel, $context);
    }

    /**
     * @param  array<string, mixed>  $context
     */
    public function warning(string $message, ?PlatformChannel $channel = null, array $context = []): void
    {
        $this->log(LogLevelEnum::WARNING, $message, $channel, $context);
    }

    /**
     * @param  array<string, mixed>  $context
     */
    public function debug(string $message, ?PlatformChannel $channel = null, array $context = []): void
    {
        $this->log(LogLevelEnum::DEBUG, $message, $channel, $context);
    }

    /**
     * @param  array<string, mixed>  $context
     */
    public function log(LogLevelEnum $level, string $message, ?PlatformChannel $channel = null, array $context = []): void
    {
        $logContext = $context;

        if ($channel) {
            $logContext = array_merge($logContext, [
                'channel_id' => $channel->id,
                'channel_name' => $channel->name,
                'platform' => $channel->platformInstance->platform->value,
                'instance_url' => $channel->platformInstance->url,
            ]);
        }

        Log::create([
            'level' => $level,
            'message' => $message,
            'context' => $logContext,
        ]);
    }
}
