<?php

namespace AutoAdmin\Bundle\Log\Monolog\Processor;

use Exception;
use Monolog\LogRecord;
use Symfony\Component\HttpFoundation\Exception\JsonException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\RequestStack;
use function in_array;

class RequestProcessor
{
    private const SYMFONY_DOTENV_VARS = 'SYMFONY_DOTENV_VARS';

    private RequestStack $requestStack;
    private ?string $requestToken = null;

    public function __construct(RequestStack $requestStack)
    {
        $this->requestStack = $requestStack;
    }

    public function __invoke(LogRecord $record)
    {
        $extra = [];

        try {
            $request = $this->requestStack->getCurrentRequest();
        } catch (Exception $e) {
            return $record;
        }

        if (null === $request) {
            return $record;
        }

        //unique request token to keep track of request between logs
        if (null === $this->requestToken) {
            $this->requestToken = uniqid('request_', true);
        }
        $extra['request_token'] = $this->requestToken;
        $extra['app_env'] = $request->server->get('APP_ENV');

        //request server info without env vars
        $envVars = explode(',', $request->server->get(self::SYMFONY_DOTENV_VARS, ''));
        $envVars[] = self::SYMFONY_DOTENV_VARS;
        foreach ($request->server->all() as $key => $value) {
            if (!in_array($key, $envVars, true)) {
                $extra['server'][$key] = $value;
            }
        }

        //request payload data
        $extra['payload']['query'] = $request->query->all();
        $extra['payload']['request'] = $request->request->all();
        $extra['payload']['body']['raw'] = $request->getContent();
        try {
            $extra['payload']['body']['array'] = $request->toArray();
        } catch (JsonException $e) {
            $extra['payload']['body']['array'] = [];
        }

//        /** @var UploadedFile $file */
//        foreach ($request->files as $file) {
//            if (!$file instanceof UploadedFile) {
//                continue;
//            }
//
//            try {
//                $extra['payload']['files'][] = [
//                    'name' => $file->getClientOriginalName(),
//                    'size' => $file->getSize(),
//                    'type' => $file->getMimeType(),
//                ];
//            } catch (\Exception $e) {
//                continue;
//            }
//        }

        $record['extra']['request'] = $extra;

        return $record;
    }
}
