CREATE TABLE IF NOT EXISTS tenant_impersonation_tokens (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    actor_tenant_id BIGINT UNSIGNED NOT NULL,
    actor_user_id BIGINT UNSIGNED NOT NULL,
    target_tenant_id BIGINT UNSIGNED NOT NULL,
    target_user_id BIGINT UNSIGNED NOT NULL,
    token_hash CHAR(64) NOT NULL,
    ip_address VARCHAR(45) NULL,
    user_agent VARCHAR(255) NULL,
    expires_at DATETIME NOT NULL,
    used_at DATETIME NULL,
    created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
    UNIQUE KEY uq_tenant_impersonation_token_hash (token_hash),
    INDEX idx_tenant_impersonation_target (target_tenant_id, expires_at, used_at),
    CONSTRAINT fk_tenant_impersonation_actor_tenant FOREIGN KEY (actor_tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
    CONSTRAINT fk_tenant_impersonation_actor_user FOREIGN KEY (actor_user_id) REFERENCES users(id) ON DELETE CASCADE,
    CONSTRAINT fk_tenant_impersonation_target_tenant FOREIGN KEY (target_tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
    CONSTRAINT fk_tenant_impersonation_target_user FOREIGN KEY (target_user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
