-- Create Database
CREATE DATABASE IF NOT EXISTS api_admin_panel;
USE api_admin_panel;

-- Admin Users Table
CREATE TABLE IF NOT EXISTS admin_users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    password_hash VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- API Keys Table
CREATE TABLE IF NOT EXISTS api_keys (
    id INT AUTO_INCREMENT PRIMARY KEY,
    api_key VARCHAR(100) NOT NULL UNIQUE,
    key_type ENUM('custom', 'automated') DEFAULT 'automated',
    service_type VARCHAR(50) DEFAULT 'all',
    allowed_ips TEXT DEFAULT NULL,
    ip_restricted BOOLEAN DEFAULT FALSE,
    expiry_date DATETIME DEFAULT NULL,
    is_active BOOLEAN DEFAULT TRUE,
    usage_count INT DEFAULT 0,
    max_usage INT DEFAULT NULL,
    created_by INT DEFAULT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

-- API Logs Table
CREATE TABLE IF NOT EXISTS api_logs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    api_key_id INT,
    ip_address VARCHAR(45),
    endpoint VARCHAR(255),
    response_status INT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (api_key_id) REFERENCES api_keys(id) ON DELETE SET NULL
);

-- Insert Default Admin (password: admin123)
INSERT INTO admin_users (username, password_hash) VALUES 
('admin', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi');

-- Insert Sample API Keys
INSERT INTO api_keys (api_key, key_type, service_type, allowed_ips, ip_restricted, expiry_date, max_usage) VALUES
('PIYUSHVIP123', 'custom', 'all', NULL, FALSE, '2027-05-06 23:59:59', NULL),
('FREEUSER456', 'custom', 'tg', NULL, FALSE, '2027-05-06 23:59:59', 100),
('piyush07', 'custom', 'num', '192.168.1.1', TRUE, '2027-05-06 23:59:59', NULL);