CREATE TABLE IF NOT EXISTS auth_refresh_tokens (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    session_id CHAR(36) NOT NULL,
    user_id BIGINT UNSIGNED NOT NULL,
    empresa_id BIGINT UNSIGNED NULL,
    token_hash CHAR(64) NOT NULL,
    ip_address VARCHAR(45) NULL,
    user_agent VARCHAR(255) NULL,
    expires_at DATETIME NOT NULL,
    last_used_at DATETIME NULL,
    revoked_at DATETIME NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NULL,
    PRIMARY KEY (id),
    UNIQUE KEY uq_auth_refresh_session (session_id),
    UNIQUE KEY uq_auth_refresh_token (token_hash),
    KEY idx_auth_refresh_user (user_id),
    KEY idx_auth_refresh_empresa (empresa_id),
    KEY idx_auth_refresh_expires (expires_at),
    CONSTRAINT fk_auth_refresh_user FOREIGN KEY (user_id) REFERENCES usuarios(id) ON DELETE CASCADE,
    CONSTRAINT fk_auth_refresh_empresa FOREIGN KEY (empresa_id) REFERENCES empresas(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
