CREATE TABLE IF NOT EXISTS products (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    code VARCHAR(20) NOT NULL UNIQUE,
    name VARCHAR(100) NOT NULL,
    key_prefix VARCHAR(10) NOT NULL,
    default_limits JSON,
    available_features JSON,
    active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS licenses (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    product_id BIGINT NOT NULL,
    license_key VARCHAR(25) NOT NULL UNIQUE,
    license_type VARCHAR(20) NOT NULL,
    customer_name VARCHAR(255) NOT NULL,
    customer_pib VARCHAR(20) DEFAULT '',
    customer_email VARCHAR(255) DEFAULT '',
    limits_json JSON NOT NULL,
    features JSON NOT NULL,
    issued_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    expires_at TIMESTAMP NULL,
    grace_days INT DEFAULT 30,
    active BOOLEAN DEFAULT TRUE,
    revoked BOOLEAN DEFAULT FALSE,
    revoked_at TIMESTAMP NULL,
    revoked_reason TEXT,
    notes TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (product_id) REFERENCES products(id),
    INDEX idx_licenses_product (product_id),
    INDEX idx_licenses_customer (customer_name),
    INDEX idx_licenses_expires (expires_at)
);

CREATE TABLE IF NOT EXISTS activations (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    license_id BIGINT NOT NULL,
    machine_fingerprint VARCHAR(100) NOT NULL,
    hostname VARCHAR(100) DEFAULT '',
    os_info VARCHAR(50) DEFAULT '',
    app_version VARCHAR(20) DEFAULT '',
    ip_address VARCHAR(45) DEFAULT '',
    activated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    deactivated_at TIMESTAMP NULL,
    is_active BOOLEAN DEFAULT TRUE,
    last_seen_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (license_id) REFERENCES licenses(id),
    INDEX idx_activations_license (license_id),
    INDEX idx_activations_fingerprint (machine_fingerprint),
    INDEX idx_activations_active (license_id, is_active)
);

CREATE TABLE IF NOT EXISTS audit_log (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    license_id BIGINT NULL,
    action VARCHAR(30) NOT NULL,
    ip_address VARCHAR(45) DEFAULT '',
    details JSON,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (license_id) REFERENCES licenses(id),
    INDEX idx_audit_license (license_id),
    INDEX idx_audit_action (action),
    INDEX idx_audit_created (created_at)
);
