<?php
/**
 * VmpFence Bot/Crawler Sync Module
 *
 * Syncs records from wp_vmpfence_crawlers to the backend
 * via POST /api/v1/firewall/bot-crawlers/batch (payload key: 'crawlers')
 *
 * @package    VMPFence
 * @subpackage Includes\Sync
 * @since      2.2.4
 */

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

class VmpFence_Bot_Crawler_Sync extends VmpFence_Base_Sync {

    /**
     * Records per API call
     * @var int
     */
    protected $batch_size = 50;

    /**
     * Constructor
     *
     * @since 2.2.4
     */
    public function __construct() {
        global $wpdb;
        $this->table_name = $wpdb->prefix . 'vmpfence_crawlers';
        parent::__construct();
    }

    /**
     * Get the API client method name for this sync module.
     *
     * @since 2.2.4
     * @return string
     */
    protected function get_endpoint_method(): string {
        return 'sync_bot_crawlers_batch';
    }

    /**
     * Transform a database row into the API payload format.
     *
     * DB Audit (Feb 16, 2026):
     * - Removed `is_verified` and `pattern_signature` — do NOT exist on BotCrawler model
     * - Added 7 required NOT NULL fields: `bot_type`, `detection_method`,
     *   `confidence_score`, `request_url`, `request_count`, `action_taken`, `first_seen`
     * - `IP` is stored as varbinary(16) — converted via format_ip()
     * - `lastUpdate` is Unix timestamp — converted via date()
     *
     * @since 2.2.4
     * @param array $row Database row
     * @return array Transformed record
     */
    protected function transform_record(array $row): array {
        $is_verified = (isset($row['status']) && $row['status'] === 'verified');

        return array(
            'plugin_event_id'  => (int) $row['id'],
            'ip_address'       => isset($row['IP']) ? $this->format_ip($row['IP']) : null,
            'user_agent'       => '',
            'bot_name'         => $row['PTR'] ?? 'unknown',
            'bot_type'         => $is_verified ? 'good' : 'unknown',
            'detection_method' => 'user_agent',
            'confidence_score' => 0,
            'request_url'      => '',
            'request_count'    => 1,
            'action_taken'     => $is_verified ? 'allowed' : 'blocked',
            'first_seen'       => isset($row['lastUpdate']) ? gmdate('Y-m-d\TH:i:s\Z', (int) $row['lastUpdate']) : current_time('c'),
            'last_seen'        => isset($row['lastUpdate']) ? gmdate('Y-m-d\TH:i:s\Z', (int) $row['lastUpdate']) : current_time('c'),
        );
    }
}
