<?php

namespace UltraguardPro\modules\ip_intelligence\db;

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

use UltraguardPro\db\BaseTable;

class IpReputationCacheTable extends BaseTable {

    protected $table_name  = 'ultraguard_ip_reputation_cache';
    protected $cache_group = 'ultraguard_ip_reputation_cache';

    public function get_defaults(): array {
        return [
            'id'           => 0,
            'ip_address'   => '',
            'abuse_score'  => 0,
            'is_threat'    => 0,
            'threat_types' => '',
            'country_code' => '',
            'isp'          => '',
            'is_tor'       => 0,
            'is_vpn'       => 0,
            'checked_at'   => '',
            'expires_at'   => '',
        ];
    }

    protected function validate_data( $data ) {
        return empty( $data['ip_address'] ) ? false : $data;
    }

    protected function sanitize_data( $data ): array {
        $out = [];
        foreach ( $data as $key => $value ) {
            if ( in_array( $key, [ 'abuse_score' ], true ) ) {
                $out[ $key ] = absint( $value );
            } elseif ( in_array( $key, [ 'is_threat', 'is_tor', 'is_vpn' ], true ) ) {
                $out[ $key ] = (int) (bool) $value;
            } elseif ( in_array( $key, [ 'checked_at', 'expires_at' ], true ) ) {
                $out[ $key ] = sanitize_text_field( (string) $value );
            } elseif ( in_array( $key, [ 'threat_types', 'isp' ], true ) ) {
                $out[ $key ] = sanitize_textarea_field( (string) $value );
            } else {
                $out[ $key ] = sanitize_text_field( (string) $value );
            }
        }
        return $out;
    }

    public function upsert_cache( array $data ): bool {
        $row = $this->get_row( [ 'ip_address' => $data['ip_address'] ] );
        if ( ! empty( $row['id'] ) ) {
            return (bool) $this->update( (int) $row['id'], $data );
        }
        return (bool) $this->insert( $data );
    }
}
