<?php

namespace PostenBringCheckout\admin\log;

use PostenBringCheckout\admin\bring\CheckoutApi;
use WC_Log_Handler_Interface;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class RemoteLogHandler implements WC_Log_Handler_Interface {
	public function handle( $timestamp, $level, $message, $context ) {
		$remote_logging_enabled = get_option( 'posten-bring-checkout-remote-log', false );
		if (
			$remote_logging_enabled &&
			isset( $context['source'] ) &&
			$context['source'] === 'posten-bring-checkout' &&
			! isset( $context['remote_log'] )
		) {
			CheckoutApi::get_instance()->remote_log(
				$message,
				$this->getLevel( $level ),
				isset( $context['backtrace'] ) ? wp_json_encode( debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS ) ) : null
			);
		}
	}

	private function getLevel( $level ): string {
		switch (strtoupper($level)) {
			case ('DEBUG'):
				return 'DEBUG';
			case ('NOTICE'):
			case ('INFO'):
				return 'INFO';
			case ('WARNING'):
				return 'WARN';
			default:
				return 'ERROR';
		}
	}
}
