-- ============================================================================
-- nbo_master — Migration 002: impersonation tokens
-- ============================================================================
-- Super-admin "login as" feature. Admin UI creates a single-use, short-lived
-- token; tenant-side impersonate.php validates it and starts a session as the
-- target tenant user — without the super admin needing the target's password.
--
-- Every impersonation is audited (master + tenant audit_log).
-- Token scoping: tied to a specific tenant AND a specific tenant-local user —
-- even if leaked, it only opens that one account on that one tenant.
-- ============================================================================

CREATE TABLE IF NOT EXISTS impersonation_tokens (
    id                    BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    token_hash            VARCHAR(80) NOT NULL UNIQUE,
    tenant_id             INT UNSIGNED NOT NULL,
    target_user_id        INT          NOT NULL,       -- tenant-local users.id
    target_global_user_id INT UNSIGNED NOT NULL,       -- nbo_master.global_users.id
    super_admin_id        INT UNSIGNED NOT NULL,       -- who created the token
    expires_at            DATETIME NOT NULL,
    used_at               DATETIME DEFAULT NULL,
    ip_address            VARCHAR(45) DEFAULT NULL,
    created_at            DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_imp_tenant  (tenant_id),
    INDEX idx_imp_expires (expires_at),
    FOREIGN KEY (tenant_id)      REFERENCES tenants(id)      ON DELETE CASCADE,
    FOREIGN KEY (super_admin_id) REFERENCES global_users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
