<?php

declare(strict_types=1);

namespace SiteFort\Modules\Cloud\Services;

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

use SiteFort\Modules\Cloud\SecureApi;
use SiteFort\Modules\Cloud\Service\CloudSettings;

/**
 * CloudScanner Service.
 *
 * Handles cloud preflight, reputation, and auxiliary intelligence calls used by
 * the scanner runtime.
 */
class CloudScanner {

    /**
     * Run preflight check to validate environment and get signature version.
     * 
     * @return array|\WP_Error Preflight result or error.
     */
    public function preflight_check() {
        $settings = CloudSettings::get_all();
        $api = new SecureApi( 
            $settings['license_key'] ?? '', 
            $settings['site_token'] ?? '',
            $settings['site_secret'] ?? ''
        );
        
        return $api->get( 'services/intelligence/scan/preflight', [], SecureApi::SCANNER_WORKER_TIMEOUT_SECONDS, SecureApi::SCANNER_WORKER_MAX_ATTEMPTS );
    }


    /**
     * Check network reputation (IP/Domain/External Links) via Cloud.
     *
     * @param string $ip Server IP.
     * @param string $domain Site Domain.
     * @param array  $ext_links External URLs found on the site.
     * @return array|\WP_Error Results or error.
     */
    public function check_reputation( string $ip, string $domain, array $ext_links = [] ) {
        $settings = CloudSettings::get_all();
        $api = new SecureApi(
            $settings['license_key'] ?? '',
            $settings['site_token'] ?? '',
            $settings['site_secret'] ?? ''
        );

        $body = [];
        if ( $ip !== '' ) {
            $body['ip'] = $ip;
        }
        if ( $domain !== '' ) {
            $body['domain'] = $domain;
        }
        if ( ! empty( $ext_links ) ) {
            $body['ext_links'] = array_values( $ext_links );
        }

        return $api->post( 'services/intelligence/reputation', $body, SecureApi::SCANNER_WORKER_TIMEOUT_SECONDS, SecureApi::SCANNER_WORKER_MAX_ATTEMPTS );
    }

    /**
     * Get suspicious/malicious WordPress usernames from Cloud.
     * Used to detect backdoor accounts created by malware.
     * Cached for 24 hours.
     * 
     * @return array List of suspicious usernames/patterns.
     */
    public function get_user_patterns() {
        $cache_key = 'sitefort_suspicious_usernames';
        $cached = get_transient( $cache_key );
        if ( is_array( $cached ) && ! empty( $cached ) ) {
            return $cached;
        }

        $settings = CloudSettings::get_all();
        $api = new SecureApi( 
            $settings['license_key'] ?? '', 
            $settings['site_token'] ?? '',
            $settings['site_secret'] ?? ''
        );
        
        $response = $api->get( 'services/intelligence/suspicious-usernames', [], SecureApi::SCANNER_WORKER_TIMEOUT_SECONDS, SecureApi::SCANNER_WORKER_MAX_ATTEMPTS );
        
        if ( ! is_wp_error( $response ) && isset( $response['users'] ) ) {
            set_transient( $cache_key, $response['users'], DAY_IN_SECONDS );
            return $response['users'];
        }

        return is_wp_error( $response ) ? $response : new \WP_Error( 'cloud_failed', 'Failed to fetch user patterns from Cloud' );
    }

    /**
     * Get weak password dictionary from Cloud.
     * Cached for 1 day.
     * 
     * @return array List of passwords.
     */
    public function get_password_dictionary() {
        $cache_key = 'sitefort_password_dict';
        $cached = get_transient( $cache_key );
        if ( is_array( $cached ) && ! empty( $cached ) ) {
            return $cached;
        }

        $settings = CloudSettings::get_all();
        $api = new SecureApi( 
            $settings['license_key'] ?? '', 
            $settings['site_token'] ?? '',
            $settings['site_secret'] ?? ''
        );
        
        $response = $api->get( 'services/intelligence/dictionary', [], SecureApi::SCANNER_WORKER_TIMEOUT_SECONDS, SecureApi::SCANNER_WORKER_MAX_ATTEMPTS );
        
        if ( ! is_wp_error( $response ) && isset( $response['passwords'] ) ) {
            set_transient( $cache_key, $response['passwords'], DAY_IN_SECONDS );
            return $response['passwords'];
        }

        return is_wp_error( $response ) ? $response : new \WP_Error( 'cloud_failed', 'Failed to fetch password dictionary from Cloud' );
    }
}
