<?php
/**
 * VirtualPatchesTable — standalone class file.
 *
 * @package UltraguardPro\modules\vulnerability\db
 */

namespace UltraguardPro\modules\vulnerability\db;

use UltraguardPro\db\BaseTable;
use UltraguardPro\core\DatabaseCrud;

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

// VirtualPatchesTable
class VirtualPatchesTable extends BaseTable {

    protected $table_name  = 'ultraguard_virtual_patches';
    protected $cache_group = 'ultraguard_virtual_patches';

    public function get_defaults(): array {
        return [
            'id'                      => 0,
            'cve_id'                  => '',
            'component_slug'          => '',
            'component_version_range' => null,
            'waf_rule_id'             => null,
            'applied_at'              => '',
            'expires_at'              => null,
            'created_at'              => '',
            'updated_at'              => '',
        ];
    }

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

    protected function sanitize_data( $data ): array {
        $out = [];
        foreach ( $data as $k => $v ) {
            if ( 'waf_rule_id' === $k ) {
                $out[ $k ] = $v === null ? null : absint( $v );
            } else {
                $out[ $k ] = is_string( $v ) ? sanitize_text_field( $v ) : $v;
            }
        }
        return $out;
    }

    /**
     * Get all non-expired active patches.
     *
     * @return array
     */
    public function get_active_patches(): array {
        return DatabaseCrud::get_records_not_expired(
            'ultraguard_virtual_patches',
            'expires_at',
            [],
            500,
            'applied_at',
            'DESC',
            ARRAY_A
        );
    }

    protected function get_searchable_fields(): array {
        return [ 'cve_id', 'component_slug' ];
    }

    protected function invalidate_caches_after_insert()    { $this->clear_all_caches(); }
    protected function invalidate_caches_after_update( $id ) { $this->clear_all_caches(); }
    protected function invalidate_caches_after_bulk()      { $this->clear_all_caches(); }
}
