meta {
  name: Get Organization Token (Refresh Token)
  type: http
  seq: 2
}

post {
  url: {{logto_endpoint}}/oidc/token
  body: formUrlEncoded
  auth: none
}

body:form-urlencoded {
  grant_type: refresh_token
  client_id: {{logto_webapp_client_id}}
  client_secret: {{logto_webapp_client_secret}}
  refresh_token: {{refresh_token}}
  resource: {{api_url}}
  organization_id: {{organization_id}}
}

script:post-response {
  if (res.body.access_token) {
    bru.setEnvVar("access_token", res.body.access_token);

    // Декодируем JWT payload для отладки
    const parts = res.body.access_token.split('.');
    if (parts.length === 3) {
      const payload = JSON.parse(Buffer.from(parts[1], 'base64').toString());
      console.log("=== ACCESS TOKEN DECODED ===");
      console.log(JSON.stringify(payload, null, 2));
      console.log("============================");
    }
  }

  // Логируем весь ответ
  console.log("=== FULL RESPONSE ===");
  console.log(JSON.stringify(res.body, null, 2));
  console.log("=====================");
}
