<?php

use Monolog\Logger;
use Buckhill\LogMe\Model\Message;
use Buckhill\LogMe\Facades\ElasticSearch;
use Buckhill\LogMe\Service\ElasticHandler;

function logme(string $message, string $type, string $index = null, int $level = null, array $context = []): array
{
    $level = $level ?? Logger::INFO;

    // If index is not specified, get the default index from config
    $index = $index ?? config('logme.default_index');

    // The record we're adding to ElasticSearch index.
    $record = [
        'message'       => $message,
        'level'         => $level,
        'level_name'    => Logger::getLevelName($level),
        'context'       => $context,
        'channel'       => $type,
        'extra'         => [
            'http' => [
                'headers' => array_only(request()->headers->all(), ['accept', 'user-agent', 'host', 'content-length', 'content-type']),
                'body' => array_except(request()->all(), ['password', 'user_password', 'pwd']),
                'ip' => request()->getClientIps()
            ]
        ]
    ];

    $message = Message::fromArray($record, $index, $type);

    return $message->index();
}

/**
 * @param string $channel
 * @param string $index
 * @param int $level
 * @return Logger
 */
function getElasticLogger(string $channel, string $index): Logger
{
    $logger = new Logger($channel);

    $handler = new ElasticHandler();

    $handler->setIndex($index)->setType($channel);

    $logger->pushHandler($handler);

    return $logger;
}