<?php

namespace UltraguardPro\modules\api_security\db;

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

use UltraguardPro\db\BaseTable;

class ApiKeysTable extends BaseTable {

    protected $table_name  = 'ultraguard_api_keys';
    protected $cache_group = 'ultraguard_api_keys';

    public function get_defaults(): array {
        return [
            'id'              => 0,
            'key_name'        => '',
            'api_key'         => '',
            'key_prefix'      => '',
            'user_id'         => 0,
            'allowed_routes'  => '',
            'allowed_methods' => '',
            'rate_limit'      => 60,
            'is_active'       => 1,
            'last_used_at'    => '',
            'expires_at'      => '',
            'created_at'      => '',
        ];
    }

    protected function validate_data( $data ) {
        return $this->validate_required( (array) $data, [ 'key_name', 'api_key', 'key_prefix' ] ) ? $data : false;
    }

    protected function sanitize_data( $data ): array {
        $out = [];
        foreach ( (array) $data as $key => $value ) {
            if ( in_array( $key, [ 'user_id', 'rate_limit', 'is_active' ], true ) ) {
                $out[ $key ] = absint( $value );
            } elseif ( in_array( $key, [ 'allowed_routes', 'allowed_methods' ], true ) ) {
                $out[ $key ] = is_string( $value ) ? wp_kses_post( $value ) : '';
            } else {
                $out[ $key ] = is_string( $value ) ? sanitize_text_field( $value ) : $value;
            }
        }

        return $out;
    }

    public function get_recent_keys( int $limit = 100 ): array {
        return (array) $this->get_by( [ 'is_active' => 1 ], max( 1, min( 250, $limit ) ), 'id', 'DESC' );
    }
}
