CREATE TABLE IF NOT EXISTS licenses (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    customer_name VARCHAR(255) NOT NULL,
    customer_email VARCHAR(255) NOT NULL DEFAULT '',
    product_code VARCHAR(64) NOT NULL,
    edition_code VARCHAR(64) NOT NULL,
    license_key VARCHAR(128) NOT NULL UNIQUE,
    duration_days INT UNSIGNED NOT NULL,
    status ENUM('ready','active','expired','revoked','disabled','cancelled') NOT NULL DEFAULT 'ready',
    activated_at DATETIME NULL,
    start_date DATETIME NULL,
    end_date DATETIME NULL,
    machine_fingerprint_hash CHAR(64) NULL,
    machine_fingerprint_json JSON NULL,
    current_installation_id VARCHAR(128) NULL,
    activation_count INT UNSIGNED NOT NULL DEFAULT 0,
    rebind_count INT UNSIGNED NOT NULL DEFAULT 0,
    max_rebinds INT UNSIGNED NOT NULL DEFAULT 10,
    last_check_at DATETIME NULL,
    notes TEXT NULL,
    created_at DATETIME NOT NULL,
    updated_at DATETIME NOT NULL,
    INDEX idx_license_status (status),
    INDEX idx_license_customer (customer_name),
    INDEX idx_last_check_at (last_check_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS license_audit_log (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    license_id INT UNSIGNED NOT NULL,
    event_type VARCHAR(64) NOT NULL,
    payload_json JSON NULL,
    created_at DATETIME NOT NULL,
    INDEX idx_audit_license (license_id),
    INDEX idx_audit_event_type (event_type),
    CONSTRAINT fk_audit_license FOREIGN KEY (license_id) REFERENCES licenses(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
