<?php

namespace Buckhill\LogMe\Service;

use Buckhill\LogMe\Model\Message;
use Buckhill\LogMe\Facades\ElasticSearch;
use Monolog\Handler\AbstractProcessingHandler;

class ElasticHandler extends AbstractProcessingHandler
{
    protected $elasticIndex;
    protected $elasticType;

    public function setIndex(string $index): self
    {
        $this->elasticIndex = $index;

        return $this;
    }

    public function setType(string $type): self
    {
        $this->elasticType = $type;

        return $this;
    }

    protected function write(array $record): void
    {
        $record['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, $this->elasticIndex, $this->elasticType);

        // Add to ES index
        ElasticSearch::index($message->getModel());
    }
}