<?php

declare(strict_types=1);
if (!defined('WPINC')) {
    die();
}

/**
 * Class CPEPAI_Logging_Service
 * Handles logging to the database log table and WordPress error log.
 */
class CPEPAI_Logging_Service
{
    /**
     * WordPress database instance
     *
     * @var wpdb
     */
    private $wpdb;

    /**
     * Database service instance
     *
     * @var CPEPAI_Database_Service
     */
    private CPEPAI_Database_Service $database_service;

    /**
     * Constructor
     *
     * @param CPEPAI_Database_Service $database_service The database service instance.
     */
    public function __construct(CPEPAI_Database_Service $database_service)
    {
        global $wpdb;
        $this->wpdb = $wpdb;
        $this->database_service = $database_service;
    }

    /**
     * Write log entry to the logs table
     *
     * @param string $level Log level (e.g., 'info', 'warning', 'error', 'debug').
     * @param string|null $event Event name or identifier.
     * @param string|null $message Log message.
     * @param array|string|null $context Additional context data (will be JSON encoded if array).
     * @param string|null $task_id Task ID associated with the log entry.
     * @param string|null $correlation_id Correlation ID for tracking related log entries.
     * @param string|null $error_code Error code if applicable.
     * @param int|null $tokens_spent Number of tokens spent for this operation.
     * @return int|false The number of rows inserted, or false on error.
     */
    public function write_to_log_table(
        string $level = 'info',
        ?string $event = null,
        ?string $message = null,
        $context = null,
        ?string $task_id = null,
        ?string $correlation_id = null,
        ?string $error_code = null,
        ?int $tokens_spent = null
    ) {
        $table_name = $this->database_service->get_logs_table_name();

        // Prepare context data
        $context_value = null;
        if ($context !== null) {
            if (is_array($context)) {
                $context_value = json_encode($context, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            } else {
                $context_value = (string) $context;
            }
        }

        // Prepare data array for insertion
        $data = [
            'level' => $level
        ];

        if ($event !== null) {
            $data['event'] = $event;
        }

        if ($message !== null) {
            $data['message'] = $message;
        }

        if ($context_value !== null) {
            $data['context'] = $context_value;
        }

        if ($task_id !== null) {
            $data['task_id'] = $task_id;
        }

        if ($correlation_id !== null) {
            $data['correlation_id'] = $correlation_id;
        }

        if ($error_code !== null) {
            $data['error_code'] = $error_code;
        }

        if ($tokens_spent !== null) {
            $data['tokens_spent'] = $tokens_spent;
        }

        // Insert into database
        $result = $this->wpdb->insert($table_name, $data);

        if ($result === false) {
            return false;
        }

        return $result;
    }

    /**
     * Write to WordPress error log if WP_DEBUG_LOG is enabled
     *
     * @param string $message The error message to log.
     * @param string|null $event Optional event identifier for context.
     * @return bool True if logged or WP_DEBUG_LOG is false, false on error.
     */
    public function write_to_error_log(string $message, ?string $event = null): bool
    {
        // Check if WP_DEBUG_LOG is enabled
        if (!defined('WP_DEBUG_LOG') || !WP_DEBUG_LOG) {
            return true; // Not an error, just not logging
        }

        // Format the log message
        $log_message = '[CPEPAI]';
        if ($event !== null) {
            $log_message .= ' [' . $event . ']';
        }
        $log_message .= ' ' . $message;

        return true; //1
    }
}
