<?php

namespace UltraguardPro\modules\traffic_monitor\db;

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

use UltraguardPro\db\BaseTable;

class TrafficLogsTable extends BaseTable {

    protected $table_name  = 'ultraguard_traffic_logs';
    protected $cache_group = 'ultraguard_traffic_logs';

    public function get_defaults(): array {
        return [
            'id'              => 0,
            'ip_address'      => '',
            'ip_country'      => '',
            'ip_country_name' => '',
            'ip_city'         => '',
            'user_agent'      => '',
            'request_method'  => '',
            'request_uri'     => '',
            'request_host'    => '',
            'referrer'        => '',
            'response_code'   => 0,
            'user_id'         => 0,
            'threat_type'     => 'clean',
            'threat_level'    => 'none',
            'was_blocked'     => 0,
            'block_reason'    => '',
            'is_bot'          => 0,
            'created_at'      => '',
        ];
    }

    protected function validate_data( $data ) {
        if ( empty( $data['ip_address'] ) || empty( $data['request_uri'] ) ) {
            return false;
        }

        return $data;
    }

    protected function sanitize_data( $data ): array {
        $out = [];

        foreach ( $data as $key => $value ) {
            switch ( $key ) {
                case 'response_code':
                case 'user_id':
                    $out[ $key ] = absint( $value );
                    break;
                case 'was_blocked':
                case 'is_bot':
                    $out[ $key ] = (int) (bool) $value;
                    break;
                case 'user_agent':
                case 'request_uri':
                case 'referrer':
                    $out[ $key ] = sanitize_textarea_field( (string) $value );
                    break;
                case 'ip_address':
                case 'ip_country':
                case 'ip_country_name':
                case 'ip_city':
                case 'request_method':
                case 'request_host':
                case 'threat_type':
                case 'threat_level':
                case 'block_reason':
                case 'created_at':
                    $out[ $key ] = sanitize_text_field( (string) $value );
                    break;
                default:
                    $out[ $key ] = is_string( $value ) ? sanitize_text_field( $value ) : $value;
                    break;
            }
        }

        return $out;
    }

    protected function invalidate_caches_after_insert() {
        // Traffic logs are high-volume writes; clearing all cached list/count
        // transients on every insert creates heavy wp_options churn and can
        // deadlock under bot/crawler traffic.
    }
}
