-- MySQL setup script for Web Hosting Panel
-- This script creates the necessary database structure for MySQL user management

-- Create the whp database if it doesn't exist
CREATE DATABASE IF NOT EXISTS whp CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE whp;

-- Table to track databases created by users
CREATE TABLE IF NOT EXISTS user_databases (
    id INT AUTO_INCREMENT PRIMARY KEY,
    database_name VARCHAR(64) NOT NULL UNIQUE,
    owner_username VARCHAR(32) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    size_bytes BIGINT DEFAULT 0,
    INDEX idx_owner (owner_username),
    INDEX idx_database (database_name)
);

-- Table to track database users created by panel users
CREATE TABLE IF NOT EXISTS database_users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(32) NOT NULL,
    host VARCHAR(255) DEFAULT '%',
    database_name VARCHAR(64) NOT NULL,
    privileges TEXT NOT NULL,
    created_by VARCHAR(32) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE KEY unique_user_host_db (username, host, database_name),
    INDEX idx_created_by (created_by),
    INDEX idx_database (database_name)
);

-- Table to store user passwords for MySQL authentication
CREATE TABLE IF NOT EXISTS user_passwords (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(32) NOT NULL UNIQUE,
    password_hash VARCHAR(255) NOT NULL,
    mysql_password VARCHAR(255) NOT NULL,
    last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_username (username)
);

-- Insert initial data if tables are empty
INSERT IGNORE INTO user_databases (database_name, owner_username) VALUES 
('test_db', 'root'),
('whp', 'root');

-- Insert initial database users if table is empty
INSERT IGNORE INTO database_users (username, database_name, privileges, created_by) VALUES 
('test_user', 'test_db', 'ALL', 'root'),
('whp_user', 'whp', 'ALL', 'root');

-- Insert root password record if it doesn't exist
INSERT IGNORE INTO user_passwords (username, password_hash, mysql_password) VALUES 
('root', 'system_password_hash', 'mysql_password'); 