<?php

namespace UltraguardPro\modules\ip_intelligence\db;

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

use UltraguardPro\db\BaseTable;

class ThreatFeedTable extends BaseTable {

    protected $table_name  = 'ultraguard_threat_feed';
    protected $cache_group = 'ultraguard_threat_feed';

    public function get_defaults(): array {
        return [
            'id'              => 0,
            'ip_address'      => '',
            'ip_type'         => 'ipv4',
            'threat_category' => '',
            'confidence'      => 50,
            'source'          => '',
            'country_code'    => '',
            'is_active'       => 1,
            'expires_at'      => null,
            'last_seen_at'    => null,
            'reports_count'   => 0,
            'created_at'      => '',
            'updated_at'      => '',
        ];
    }

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

        return $data;
    }

    protected function sanitize_data( $data ): array {
        $out = [];
        foreach ( $data as $key => $value ) {
            if ( in_array( $key, [ 'confidence', 'reports_count' ], true ) ) {
                $out[ $key ] = absint( $value );
            } elseif ( 'is_active' === $key ) {
                $out[ $key ] = (int) (bool) $value;
            } elseif ( in_array( $key, [ 'expires_at', 'last_seen_at' ], true ) ) {
                $out[ $key ] = empty( $value ) ? null : sanitize_text_field( (string) $value );
            } else {
                $out[ $key ] = sanitize_text_field( (string) $value );
            }
        }
        return $out;
    }

    public function upsert_feed_entry( array $data ): bool {
        $row   = $this->get_row( [ 'ip_address' => $data['ip_address'], 'source' => $data['source'] ] );

        if ( ! empty( $row['id'] ) ) {
            return (bool) $this->update( (int) $row['id'], $data );
        }

        return false !== $this->insert( $data );
    }
}
