<?php

namespace FleekDash\Core;

use WP_REST_Request;
use WP_REST_Response;

/**
 * Clear / delete debug.log operations shared across debug handlers.
 * Extracted from DebugController for S1448 compliance.
 */
class DebugLogService
{
    private const DEBUG_LOG_FILE = '/debug.log';

    private const MSG_BY_USER_ID = ' by user ID ';

    /**
     * Clear or delete the debug.log file.
     *
     * @param bool $deleteFile Whether to delete the file completely
     * @param bool $createBackup Whether to create a backup before clearing
     * @return array<string, mixed>
     */
    public function clearDebugLog($deleteFile = false, $createBackup = false)
    {
        $debugLogPath = WP_CONTENT_DIR . self::DEBUG_LOG_FILE;
        $result = [
            'success' => false,
            'action' => '',
            'file_existed' => false,
            'file_size' => 0,
            'backup_created' => false,
            'backup_path' => '',
        ];

        if (!file_exists($debugLogPath)) {
            $result['success'] = true;
            $result['action'] = 'no_file';
            return $result;
        }

        $result['file_existed'] = true;
        $result['file_size'] = filesize($debugLogPath);

        try {
            if ($createBackup && $result['file_size'] > 0) {
                $backupPath = WP_CONTENT_DIR . '/debug-backup-' . date('Y-m-d-H-i-s') . '.log';
                if (copy($debugLogPath, $backupPath)) {
                    $result['backup_created'] = true;
                    $result['backup_path'] = $backupPath;
                }
            }

            if ($deleteFile) {
                if (unlink($debugLogPath)) {
                    $result['success'] = true;
                    $result['action'] = 'deleted';
                }
            } elseif (file_put_contents($debugLogPath, '') !== false) {
                $result['success'] = true;
                $result['action'] = 'cleared';
            }
        } catch (\Exception $e) {
            fleekdash_log_error('FleekDash Debug: Error clearing debug.log - ' . $e->getMessage());
            $result['error'] = $e->getMessage();
        }

        return $result;
    }

    /**
     * REST endpoint: clear debug log.
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response
     */
    public function clearDebugLogEndpoint(WP_REST_Request $request)
    {
        try {
            $deleteFile = $request->get_param('delete_file') ?? false;
            $createBackup = $request->get_param('create_backup') ?? false;
            $result = $this->clearDebugLog($deleteFile, $createBackup);

            if (!$result['success']) {
                return new WP_REST_Response([
                    'success' => false,
                    'message' => 'Failed to clear debug log: ' . ($result['error'] ?? 'Unknown error'),
                    'data' => $result,
                ], 500);
            }

            $message = $this->resolveClearLogMessage($result);

            fleekdash_log_info('FleekDash Debug: Debug log manually ' . $result['action'] .
                self::MSG_BY_USER_ID . \get_current_user_id());

            return new WP_REST_Response([
                'success' => true,
                'message' => $message,
                'data' => $result,
            ], 200);
        } catch (\Exception $e) {
            fleekdash_log_error('FleekDash Debug: Error in clear_debug_log_endpoint - ' . $e->getMessage());

            return new WP_REST_Response([
                'success' => false,
                'message' => 'Error clearing debug log: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * @param array<string, mixed> $result
     */
    private function resolveClearLogMessage(array $result)
    {
        $action = $result['action'] ?? '';
        $messages = [
            'no_file' => 'Debug log file does not exist',
            'cleared' => 'Debug log cleared successfully',
            'deleted' => 'Debug log file deleted successfully',
        ];
        $message = $messages[$action] ?? 'Unknown action';

        if (!empty($result['backup_created'])) {
            $message .= ' (backup created)';
        }

        return $message;
    }
}
