CREATE DATABASE license_system CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE license_system;

-- جدول محصولات
CREATE TABLE products (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    slug VARCHAR(100) UNIQUE NOT NULL,
    current_version VARCHAR(20) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;

-- جدول نسخه‌های محصول
CREATE TABLE versions (
    id INT AUTO_INCREMENT PRIMARY KEY,
    product_id INT NOT NULL,
    version VARCHAR(20) NOT NULL,
    changelog TEXT,
    file_path VARCHAR(500) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE
) ENGINE=InnoDB;

-- جدول لایسنس‌ها
CREATE TABLE licenses (
    id INT AUTO_INCREMENT PRIMARY KEY,
    license_key VARCHAR(100) UNIQUE NOT NULL,
    product_id INT NOT NULL,
    domain VARCHAR(255) DEFAULT NULL,
    status ENUM('pending', 'active', 'expired', 'blocked') DEFAULT 'pending',
    max_activations INT DEFAULT 1,
    activation_count INT DEFAULT 0,
    expires_at DATETIME DEFAULT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE,
    INDEX idx_license_key (license_key),
    INDEX idx_domain (domain)
) ENGINE=InnoDB;

-- جدول لاگ‌ها
CREATE TABLE license_logs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    license_id INT,
    action VARCHAR(50) NOT NULL,
    domain VARCHAR(255),
    ip_address VARCHAR(45),
    user_agent TEXT,
    request_data TEXT,
    response_data TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (license_id) REFERENCES licenses(id) ON DELETE SET NULL,
    INDEX idx_action (action),
    INDEX idx_created (created_at)
) ENGINE=InnoDB;