-- Create user_api_tokens table for API token management
-- This table stores user-generated API tokens for programmatic access

CREATE TABLE IF NOT EXISTS `user_api_tokens` (
    `id` INT AUTO_INCREMENT PRIMARY KEY,
    `user_id` INT NOT NULL,
    `token_id` VARCHAR(64) UNIQUE NOT NULL,
    `name` VARCHAR(255) NOT NULL,
    `allowed_urls` TEXT NULL,
    `is_active` BOOLEAN DEFAULT TRUE,
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    `last_used` TIMESTAMP NULL,
    
    -- Indexes for performance
    INDEX `idx_user_id` (`user_id`),
    INDEX `idx_token_id` (`token_id`),
    INDEX `idx_is_active` (`is_active`),
    
    -- Foreign key constraint (removed to avoid dependency issues)
    -- The application will handle referential integrity
    KEY `fk_user_api_tokens_user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Create api_usage_log table for tracking API usage
CREATE TABLE IF NOT EXISTS `api_usage_log` (
    `log_id` INT AUTO_INCREMENT PRIMARY KEY,
    `token_id` VARCHAR(64) NOT NULL,
    `user_id` INT NOT NULL,
    `endpoint` VARCHAR(255) NOT NULL,
    `request_time` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    `response_time` DECIMAL(10,3) NULL,
    `status_code` INT NOT NULL,
    `ip_address` VARCHAR(45) NULL,
    `user_agent` TEXT NULL,
    `data_transfer_bytes` BIGINT DEFAULT 0,
    
    -- Indexes for performance
    INDEX `idx_token_id` (`token_id`),
    INDEX `idx_user_id` (`user_id`),
    INDEX `idx_request_time` (`request_time`),
    INDEX `idx_endpoint` (`endpoint`),
    INDEX `idx_status_code` (`status_code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
