<?php

namespace UltraguardPro\modules\api_security\schema;

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

use UltraguardPro\modules\core\AbstractModuleSchema;

class ApiSecuritySchema extends AbstractModuleSchema {

    public function get_module_id(): string {
        return 'api_security';
    }

    public function get_table_map(): array {
        return [
            'api_keys'        => \UltraguardPro\modules\api_security\db\ApiKeysTable::class,
            'api_request_log' => \UltraguardPro\modules\api_security\db\ApiRequestLogTable::class,
        ];
    }

    public function get_schemas(): array {
        $cs = $this->charset_collate();

        return [
            $this->table( 'ultraguard_api_keys' ) =>
            "CREATE TABLE {$this->table('ultraguard_api_keys')} (
  id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  key_name varchar(100) NOT NULL,
  api_key varchar(64) NOT NULL,
  key_prefix varchar(8) NOT NULL,
  user_id bigint(20) UNSIGNED DEFAULT NULL,
  allowed_routes text DEFAULT NULL,
  allowed_methods text DEFAULT NULL,
  rate_limit int(10) UNSIGNED NOT NULL DEFAULT 60,
  is_active tinyint(1) NOT NULL DEFAULT 1,
  last_used_at datetime DEFAULT NULL,
  expires_at datetime DEFAULT NULL,
  created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY idx_api_key (api_key),
  KEY idx_is_active (is_active),
  KEY idx_user_id (user_id)
) {$cs};",
            $this->table( 'ultraguard_api_request_log' ) =>
            "CREATE TABLE {$this->table('ultraguard_api_request_log')} (
  id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  endpoint varchar(500) NOT NULL,
  method varchar(10) NOT NULL,
  ip_address varchar(45) NOT NULL,
  auth_type varchar(20) DEFAULT 'none',
  key_id bigint(20) UNSIGNED DEFAULT NULL,
  response_code smallint(5) UNSIGNED DEFAULT NULL,
  was_blocked tinyint(1) NOT NULL DEFAULT 0,
  block_reason varchar(100) DEFAULT NULL,
  request_type varchar(20) NOT NULL DEFAULT 'rest',
  created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_endpoint (endpoint(191)),
  KEY idx_ip_address (ip_address),
  KEY idx_was_blocked (was_blocked),
  KEY idx_created_at (created_at)
) {$cs};",
        ];
    }
}
