<?php

namespace Twnt4All\Engine\Adapter;

use Twnt4All\Engine\Contract\ConfigProviderInterface;
use Twnt4All\Engine\Contract\LoggerInterface;
use Twnt4All\Support\Journal;

/**
 * Class DirectLogger
 * @package Twnt4All\Engine\Adapter
 */
class DirectLogger implements LoggerInterface
{
    /**
     * Logs an error.
     *
     * @param $title
     * @param string|array $error
     * @param ConfigProvider|null $data_provider
     * @param null $caller
     */
    public static function log_error( $title, $error, $data_provider = null, $caller = null )
    {
        if ( !$caller ) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace -- capturing the caller frame for structured log entries; not a debug print.
            $backtrace = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 2 );
            $caller    = array_shift( $backtrace );
        }

        Journal::error( static::get_formatted_log( $title, $error, $data_provider ), $caller );
    }

    /**
     * Logs other events.
     *
     * @param $title
     * @param string|array $event
     * @param ConfigProvider|int|string|null $data_provider
     * @param null $caller
     */
    public static function log_event( $title, $event, $data_provider = null, $caller = null )
    {
        if ( !$caller ) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace -- capturing the caller frame for structured log entries; not a debug print.
            $backtrace = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 2 );
            $caller    = array_shift( $backtrace );
        }

        Journal::event( static::get_formatted_log( $title, $event, $data_provider ), $caller );
    }

    /**
     * @param $title
     * @param $content
     * @param $data_provider
     * @return string
     */
    private static function get_formatted_log( $title, $content, $data_provider = null )
    {
        if ( !is_string( $content ) ) {
            $content = json_encode( $content );
        }

        $log = sprintf( '%1$s: %2$s', $title, $content );

        if ( $data_provider instanceof ConfigProviderInterface ) {
            $log = sprintf( '[order_id=%1$s][pid=%2$s]', $data_provider->get_order_id(), $data_provider->get_process_id() ) . $log;
        } elseif ( is_string( $data_provider ) || is_int( $data_provider ) ) {
            $log = sprintf( '[order_id=%1$s]', $data_provider ) . $log;
        }

        return $log;
    }
}
