-- API Keys Hardening Migration
-- Add security fields to api_keys table

ALTER TABLE api_keys 
ADD COLUMN IF NOT EXISTS rate_limit_per_minute INT DEFAULT 100 COMMENT 'Rate limit per minute (default: 100)',
ADD COLUMN IF NOT EXISTS rate_limit_window INT DEFAULT 60 COMMENT 'Rate limit window in seconds (default: 60)',
ADD COLUMN IF NOT EXISTS enable_ip_whitelist TINYINT(1) DEFAULT 0 COMMENT 'Enable IP whitelist (0=disabled, 1=enabled)',
ADD COLUMN IF NOT EXISTS ip_whitelist TEXT NULL COMMENT 'IP whitelist (comma-separated or JSON array). Support CIDR notation.',
ADD COLUMN IF NOT EXISTS expires_at DATETIME NULL COMMENT 'API key expiration date (NULL = never expires)',
ADD COLUMN IF NOT EXISTS last_used_at DATETIME NULL COMMENT 'Last time API key was used',
ADD COLUMN IF NOT EXISTS created_at DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT 'API key creation date',
ADD COLUMN IF NOT EXISTS updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Last update date';

-- Index untuk performa
CREATE INDEX IF NOT EXISTS idx_api_keys_expires_at ON api_keys(expires_at);
CREATE INDEX IF NOT EXISTS idx_api_keys_is_active ON api_keys(is_active);
CREATE INDEX IF NOT EXISTS idx_api_keys_last_used_at ON api_keys(last_used_at);

-- Update last_used_at saat API key digunakan (akan di-handle di code)
-- Trigger bisa ditambahkan jika diperlukan
