<?php

namespace FleekDash\Core;

use WP_REST_Request;
use WP_REST_Response;

/**
 * Handles debug log auto-clear logic.
 * Extracted from DebugController for S1448 compliance (method count).
 */
class DebugAutoClearHandler
{
    private const DEBUG_LOG_FILE = '/debug.log';

    private const AUTO_CLEAR_OPTIONS = [
        'auto_clear_enabled' => false,
        'auto_clear_on_toggle' => true,
        'auto_clear_max_size_mb' => 10,
        'auto_clear_max_age_hours' => 24,
        'auto_clear_backup' => true,
    ];

    /** @var DebugLogService */
    private $logService;

    public function __construct(DebugLogService $logService)
    {
        $this->logService = $logService;
    }

    /**
     * Initialize auto-clear system - check on each request
     */
    public function initAutoClearSystem(): void
    {
        if ($this->shouldAutoClear()) {
            $this->performAutoClear();
        }
    }

    /**
     * Handle debug mode changes for auto-clear.
     *
     * @param bool $previousEnabled Previous debug mode state
     * @param bool $newEnabled New debug mode state
     */
    public function handleDebugModeChange(bool $previousEnabled, bool $newEnabled): void
    {
        $settings = $this->getAutoClearSettingsData();

        if ($settings['auto_clear_on_toggle']) {
            $this->logService->clearDebugLog(false, $settings['auto_clear_backup']);
            if (function_exists('fleekdash_log_info')) {
                fleekdash_log_info(
                    'FleekDash Debug: Auto-cleared debug.log due to debug mode toggle ('
                    . ($previousEnabled ? 'on' : 'off') . ' -> ' . ($newEnabled ? 'on' : 'off') . ')',
                );
            }
        }
    }

    /**
     * Get auto-clear settings endpoint
     */
    public function getAutoClearSettings(): WP_REST_Response
    {
        try {
            $settings = $this->getAutoClearSettingsData();
            return new WP_REST_Response(['success' => true, 'data' => $settings], 200);
        } catch (\Exception $e) {
            if (function_exists('fleekdash_log_error')) {
                fleekdash_log_error('FleekDash Debug: Error getting auto-clear settings - ' . $e->getMessage());
            }
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Failed to get auto-clear settings: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Update auto-clear settings endpoint
     */
    public function updateAutoClearSettings(WP_REST_Request $request): WP_REST_Response
    {
        try {
            $settings = $this->getAutoClearSettingsData();
            $updated_settings = [];
            foreach (self::AUTO_CLEAR_OPTIONS as $key => $default_value) {
                $param_value = $request->get_param($key);
                $updated_settings[$key] = $param_value !== null ? $param_value : $settings[$key];
            }
            \update_option('fleekdash_auto_clear_settings', $updated_settings);
            if (function_exists('fleekdash_log_info')) {
                fleekdash_log_info('FleekDash Debug: Auto-clear settings updated by user ID ' . \get_current_user_id());
            }
            return new WP_REST_Response([
                'success' => true,
                'message' => 'Auto-clear settings updated successfully',
                'data' => $updated_settings,
            ], 200);
        } catch (\Exception $e) {
            if (function_exists('fleekdash_log_error')) {
                fleekdash_log_error('FleekDash Debug: Error updating auto-clear settings - ' . $e->getMessage());
            }
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Failed to update auto-clear settings: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Trigger manual auto-clear check endpoint
     */
    public function triggerAutoClearCheck(): WP_REST_Response
    {
        try {
            if ($this->shouldAutoClear()) {
                $result = $this->performAutoClear();
                return new WP_REST_Response([
                    'success' => true,
                    'message' => 'Auto-clear triggered successfully',
                    'data' => $result,
                ], 200);
            }
            return new WP_REST_Response([
                'success' => true,
                'message' => 'Auto-clear conditions not met',
                'data' => [
                    'auto_clear_performed' => false,
                    'reason' => 'File size and age within limits',
                ],
            ], 200);
        } catch (\Exception $e) {
            if (function_exists('fleekdash_log_error')) {
                fleekdash_log_error('FleekDash Debug: Error triggering auto-clear check - ' . $e->getMessage());
            }
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Failed to trigger auto-clear check: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * @return array<string, mixed>
     */
    private function getAutoClearSettingsData(): array
    {
        $settings = \get_option('fleekdash_auto_clear_settings', []);
        if (!is_array($settings)) {
            $settings = [];
        }
        return array_merge(self::AUTO_CLEAR_OPTIONS, $settings);
    }

    private function shouldAutoClear(): bool
    {
        $settings = $this->getAutoClearSettingsData();
        if (!$settings['auto_clear_enabled']) {
            return false;
        }
        $debug_log_path = WP_CONTENT_DIR . self::DEBUG_LOG_FILE;
        if (!file_exists($debug_log_path)) {
            return false;
        }
        $file_size_mb = filesize($debug_log_path) / (1024 * 1024);
        $file_age_hours = (time() - filemtime($debug_log_path)) / 3600;
        return $file_size_mb >= $settings['auto_clear_max_size_mb']
            || $file_age_hours >= $settings['auto_clear_max_age_hours'];
    }

    /**
     * @return array<string, mixed>
     */
    private function performAutoClear(): array
    {
        $settings = $this->getAutoClearSettingsData();
        $result = $this->logService->clearDebugLog(false, $settings['auto_clear_backup']);
        if (is_array($result) && ($result['success'] ?? false) && function_exists('fleekdash_log_info')) {
            fleekdash_log_info('FleekDash Debug: Auto-cleared debug.log - ' . ($result['action'] ?? '') .
                ' (size: ' . round(($result['file_size'] ?? 0) / (1024 * 1024), 2) . 'MB)');
        }
        return is_array($result) ? $result : [];
    }
}
