Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

226 KB
Raw Blame
(ns metabase-enterprise.dependencies.api-test
  (:require
   [clojure.test :refer :all]
   [medley.core :as m]
   [metabase-enterprise.data-apps.test-util :as data-apps.tu]
   [metabase-enterprise.dependencies.analysis-finding :as deps.analysis-finding]
   [metabase-enterprise.dependencies.api :as deps.api]
   [metabase-enterprise.dependencies.calculation :as deps.calculation]
   [metabase-enterprise.dependencies.db :as dependencies.db]
   [metabase-enterprise.dependencies.hooks :as deps.hooks]
   [metabase-enterprise.dependencies.test-util :as deps.test]
   [metabase.collections.models.collection :as collection]
   [metabase.collections.test-utils :refer [personal-collection-id]]
   [metabase.config.core :as config]
   [metabase.core.core :as mbc]
   [metabase.events.core :as events]
   [metabase.lib-be.core :as lib-be]
   [metabase.lib.core :as lib]
   [metabase.lib.metadata :as lib.metadata]
   [metabase.permissions.core :as perms]
   [metabase.permissions.models.permissions-group :as perms-group]
   [metabase.queries.models.card :as card]
   [metabase.test :as mt]
   [metabase.util :as u]
   [toucan2.core :as t2]))

(defn- card-with-query
  "Create a card map with the given name and dataset query."
  [card-name dataset-query]
  {:name card-name
   :database_id (mt/id)
   :display :table
   :query_type :query
   :type :question
   :dataset_query dataset-query
   :visualization_settings {}})

(defn- basic-card
  "Construct a basic card for dependency testing."
  ([]
   (basic-card "Test card"))
  ([card-name]
   (basic-card card-name :orders))
  ([card-name table-keyword]
   (let [mp (mt/metadata-provider)]
     (card-with-query card-name (lib/query mp (lib.metadata/table mp (mt/id table-keyword)))))))

(defn- wrap-card-query
  "Construct a query depending on `inner-card` for dependency testing."
  [inner-card]
  (let [mp (mt/metadata-provider)
        card-meta (lib.metadata/card mp (:id inner-card))]
    (lib/query mp card-meta)))

(defn- wrap-card
  "Construct a card depending on `inner-card` for dependency testing."
  [inner-card]
  (card-with-query "Downstream card" (wrap-card-query inner-card)))

(defn- wrap-two-cards
  "Construct a card depending on both `card1` and `card2` via a join."
  [card1 card2]
  (let [mp (mt/metadata-provider)
        card1-meta (lib.metadata/card mp (:id card1))
        card2-meta (lib.metadata/card mp (:id card2))
        base-query (lib/query mp card1-meta)
        card1-cols (lib/returned-columns base-query card1-meta)
        card2-cols (lib/returned-columns base-query card2-meta)
        join-clause (-> (lib/join-clause card2-meta)
                        (lib/with-join-alias "joined")
                        (lib/with-join-conditions
                         [(lib/= (first card1-cols)
                                 (-> (first card2-cols)
                                     (lib/with-join-alias "joined")))])
                        (lib/with-join-fields :all))]
    (card-with-query "Card with join" (lib/join base-query join-clause))))

(defn- create-model-card!
  "Create a model card with the given name and optional collection-id.
   Returns the created card."
  [user card-name & {:keys [collection-id archived]}]
  (let [mp (mt/metadata-provider)
        orders (lib.metadata/table mp (mt/id :orders))]
    (card/create-card! (m/assoc-some {:name card-name
                                      :database_id (mt/id)
                                      :display :table
                                      :query_type :query
                                      :type :model
                                      :dataset_query (lib/query mp orders)
                                      :visualization_settings {}}
                                     :collection_id collection-id
                                     :archived archived)
                       user)))

(defn- create-dependent-card-on-model!
  [user model-card card-name & {:keys [collection-id table] :or {table :orders}}]
  (let [mp (mt/metadata-provider)
        model-meta (lib.metadata/card mp (:id model-card))
        q (lib/query mp model-meta)
        cols (lib/filterable-columns q)
        filter-col-name (case table
                          :products :price
                          :total)

        filter-col (m/find-first #(= (:id %) (mt/id table filter-col-name)) cols)
        dependent-query (lib/filter q (lib/> filter-col 100))]
    (card/create-card! (cond-> (card-with-query card-name dependent-query)
                         collection-id (assoc :collection_id collection-id))
                       user)))

(defn- edge-present?
  "Returns true if `edges` contains an edge from (`from-type` `from-id`) to (`to-type` `to-id`)."
  [edges from-type from-id to-type to-id]
  (boolean (some #(and (= (:from_entity_type %) from-type)
                       (= (:from_entity_id %) from-id)
                       (= (:to_entity_type %) to-type)
                       (= (:to_entity_id %) to-id))
                 edges)))

(defn- break-model-card!
  "Update a model card to query the products table instead of orders.
   This breaks any downstream cards that depend on columns only in the orders table (like TOTAL)."
  [model-card]
  (let [mp (mt/metadata-provider)
        products (lib.metadata/table mp (mt/id :products))]
    (card/update-card! {:card-before-update model-card
                        :card-updates {:dataset_query (lib/query mp products)}})))

(defn- run-analysis-for-card!
  "Run analysis for a specific card to detect broken references.
   Must be called within lib-be/with-metadata-provider-cache."
  [card-id]
  (deps.analysis-finding/upsert-analysis! (t2/select-one :model/Card :id card-id)))

(deftest graph-test
  (testing "GET /api/ee/dependencies/graph"
    (mt/with-premium-features #{:dependencies}
      (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus]
        (mt/with-temp [:model/User user {:email "[email protected]"}]
          (let [{card-id-1 :id :as dependency-card} (card/create-card! (basic-card) user)
                {card-id-2 :id} (card/create-card! (wrap-card dependency-card) user)
                _ (deps.test/synchronously-run-dependency-job!)
                response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph" :id card-id-2 :type "card")
                creator {:email "[email protected]"
                         :id (:id user)}]
            (is (=? {:edges
                     #{{:from_entity_id card-id-2, :from_entity_type "card"
                        :to_entity_id card-id-1, :to_entity_type "card"}
                       {:from_entity_id card-id-1, :from_entity_type "card"
                        :to_entity_id (mt/id :orders), :to_entity_type "table"}}
                     :nodes
                     [{:data {:collection
                              {:metabase.collections.models.collection.root/is-root? true}
                              :collection_id nil
                              :creator creator
                              :database_id (mt/id)
                              :last-edit-info creator}
                       :dependents_count {:question 1}
                       :id card-id-1
                       :type "card"}
                      {:data {:collection
                              {:metabase.collections.models.collection.root/is-root? true}
                              :creator creator
                              :database_id (mt/id)
                              :last-edit-info creator
                              :name "Downstream card"}
                       :dependents_count nil
                       :id card-id-2
                       :type "card"}
                      {:data {:db
                              {:id (mt/id)}
                              :db_id (mt/id)}
                       :dependents_count {:question int?}
                       :id (mt/id :orders)
                       :type "table"}]}
                    (-> response
                        (update :edges set)
                        (update :nodes #(sort-by (juxt :type :id) %)))))))))))

(deftest graph-transform-hydrates-creator-test
  (testing "GET /api/ee/dependencies/graph hydrates creator for transforms"
    (mt/with-premium-features #{:dependencies :transforms-basic :hosting}
      (mt/with-temp [:model/Transform {transform-id :id} {:name "Test Transform"
                                                          :creator_id (mt/user->id :crowberto)}]
        (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph"
                                             :id transform-id
                                             :type "transform")
              transform-node (first (filter #(= (:type %) "transform") (:nodes response)))
              crowberto-id (mt/user->id :crowberto)]
          (testing "Transform node has creator hydrated"
            (is (some? transform-node))
            (is (map? (get-in transform-node [:data :creator])))
            (is (= crowberto-id (get-in transform-node [:data :creator :id])))))))))

(deftest graph-table-root-test
  (testing "GET /api/ee/dependencies/graph with table as root node"
    (mt/dataset test-data
      (mt/with-premium-features #{:dependencies}
        (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus]
          (mt/with-temp [:model/User user {:email "[email protected]"}]
            (let [_card-1 (card/create-card! (basic-card "Card 1" :orders) user)
                  _card-2 (card/create-card! (basic-card "Card 2" :orders) user)
                  _ (deps.test/synchronously-run-dependency-job!)
                  response (mt/user-http-request :rasta :get 200 "ee/dependencies/graph"
                                                 :id (mt/id :orders)
                                                 :type "table")]
              (testing "table has no upstream dependencies, so only the table node is returned"
                (is (=? {:nodes [{:id (mt/id :orders)
                                  :type "table"
                                  :data {:db_id (mt/id)}
                                  :dependents_count {:question #(and (int? %) (>= % 2))}}]
                         :edges #{}}
                        (update response :edges set)))))))))))

(deftest ^:synchronized table-dependents-all-types-test
  (testing "GET /api/ee/dependencies/graph dependents_count types every non-card dependent kind for a table root"
    (mt/with-premium-features #{:dependencies :transforms-basic}
      (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus
                              :model/Transform :model/Segment :model/Measure]
        (mt/with-test-user :crowberto
          (let [mp          (mt/metadata-provider)
                products-id (mt/id :products)
                products    (lib.metadata/table mp products-id)
                price       (lib.metadata/field mp (mt/id :products :price))
                user        (mt/fetch-user :crowberto)]
            (card/create-card! (assoc (card-with-query "Question on products" (lib/query mp products))
                                      :type :question)
                               user)
            (card/create-card! (assoc (card-with-query "Model on products" (lib/query mp products))
                                      :type :model)
                               user)
            (card/create-card! (assoc (card-with-query "Metric on products"
                                                       (-> (lib/query mp products)
                                                           (lib/aggregate (lib/count))))
                                      :type :metric)
                               user)
            (mt/with-temp [:model/Segment {:as segment} {:name "Segment on products"
                                                         :table_id products-id
                                                         :definition (-> (lib/query mp products)
                                                                         (lib/filter (lib/> price 50))
                                                                         lib/->legacy-MBQL
                                                                         :query)}
                           :model/Measure {:as measure} {:name "Measure on products"
                                                         :table_id products-id
                                                         :definition (-> (lib/query mp products)
                                                                         (lib/aggregate (lib/sum price)))}
                           :model/Transform _ {:name   "Transform on products"
                                               :source {:type :query :query (lib/query mp products)}
                                               :target {:type "table" :name (mt/random-name)}}]
              (events/publish-event! :event/segment-create {:object segment :user-id (mt/user->id :crowberto)})
              (events/publish-event! :event/measure-create {:object measure :user-id (mt/user->id :crowberto)})
              (deps.test/synchronously-run-dependency-job!)
              (let [response   (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph"
                                                     :id products-id :type "table")
                    table-node (first (filter #(= (:id %) products-id) (:nodes response)))]
                (testing "the table's dependents_count includes every dependent kind, correctly typed"
                  (is (=? {:question  pos-int?
                           :model     pos-int?
                           :metric    pos-int?
                           :segment   pos-int?
                           :measure   pos-int?
                           :transform pos-int?}
                          (:dependents_count table-node))))))))))))

(deftest dependents-test
  (testing "GET /api/ee/dependencies/graph/dependents"
    (mt/with-premium-features #{:dependencies}
      (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus]
        (mt/with-temp [:model/User user {:email "[email protected]"}]
          (let [{card-id-1 :id :as dependency-card} (card/create-card! (basic-card) user)
                {card-id-2 :id} (card/create-card! (wrap-card dependency-card) user)
                _ (deps.test/synchronously-run-dependency-job!)
                response (mt/user-http-request :rasta :get 200 "ee/dependencies/graph/dependents"
                                               :id card-id-1
                                               :type "card"
                                               :dependent-types "card"
                                               :dependent-card-types "question")]
            (is (=? [{:data
                      {:collection
                       {:id "root"
                        :metabase.collections.models.collection.root/is-root? true}
                       :creator
                       {:email "[email protected]"
                        :id (:id user)}
                       :database_id (mt/id)
                       :display "table"
                       :last-edit-info
                       {:email "[email protected]"
                        :id (:id user)}
                       :name "Downstream card"
                       :type "question"}
                      :dependents_count nil
                      :id card-id-2
                      :type "card"}]
                    response))))))))

(deftest ^:synchronized dependents-multiple-types-test
  (testing "GET /api/ee/dependencies/graph/dependents with multiple dependent-types"
    (mt/with-premium-features #{:dependencies}
      (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus :model/DashboardCard]
        (mt/with-temp [:model/User user {:email "[email protected]"}
                       :model/Dashboard {dashboard-id :id} {:name "Test Dashboard"}]
          (let [{card-id-1 :id :as dependency-card} (card/create-card! (basic-card "Base card - multi") user)
                _dependent-card (card/create-card! (wrap-card dependency-card) user)]
            (t2/insert! :model/DashboardCard {:dashboard_id dashboard-id
                                              :card_id card-id-1
                                              :row 0
                                              :col 0
                                              :size_x 4
                                              :size_y 4})
            (events/publish-event! :event/dashboard-update {:object (t2/select-one :model/Dashboard :id dashboard-id) :user-id (mt/user->id :crowberto)})
            (deps.test/synchronously-run-dependency-job!)
            (testing "single dependent-types value (backward compatibility)"
              (let [response (mt/user-http-request :rasta :get 200 "ee/dependencies/graph/dependents"
                                                   :id card-id-1
                                                   :type "card"
                                                   :dependent-types "card")]
                (is (= 1 (count response)))
                (is (every? #(= "card" (:type %)) response))))
            (testing "multiple dependent-types via repeated params"
              (let [response (mt/user-http-request :rasta :get 200 "ee/dependencies/graph/dependents"
                                                   :id card-id-1
                                                   :type "card"
                                                   :dependent-types "card"
                                                   :dependent-types "dashboard")]
                (is (= 2 (count response)))
                (is (= #{"card" "dashboard"} (set (map :type response))))))
            (testing "no dependent-types returns all types"
              (let [response (mt/user-http-request :rasta :get 200 "ee/dependencies/graph/dependents"
                                                   :id card-id-1
                                                   :type "card")]
                (is (>= (count response) 2))
                (is (contains? (set (map :type response)) "card"))
                (is (contains? (set (map :type response)) "dashboard"))))))))))

(deftest ^:synchronized dependents-multiple-card-types-test
  (testing "GET /api/ee/dependencies/graph/dependents with multiple dependent-card-types"
    (mt/with-premium-features #{:dependencies}
      (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus]
        (mt/with-temp [:model/User user {:email "[email protected]"}]
          (let [{dependency-card-id :id :as dependency-card} (card/create-card! (basic-card "Base card - cardtypes") user)
                _question-card (card/create-card! (assoc (wrap-card dependency-card) :name "Question card") user)
                _model-card (card/create-card! (assoc (wrap-card dependency-card) :name "Model card" :type :model) user)]
            (deps.test/synchronously-run-dependency-job!)
            (testing "single dependent-card-types value"
              (let [response (mt/user-http-request :rasta :get 200 "ee/dependencies/graph/dependents"
                                                   :id dependency-card-id
                                                   :type "card"
                                                   :dependent-types "card"
                                                   :dependent-card-types "question")]
                (is (= 1 (count response)))
                (is (= "question" (-> response first :data :type)))))
            (testing "multiple dependent-card-types via repeated params"
              (let [response (mt/user-http-request :rasta :get 200 "ee/dependencies/graph/dependents"
                                                   :id dependency-card-id
                                                   :type "card"
                                                   :dependent-types "card"
                                                   :dependent-card-types "question"
                                                   :dependent-card-types "model")]
                (is (= 2 (count response)))
                (is (= #{"question" "model"} (set (map #(-> % :data :type) response))))))
            (testing "no dependent-card-types returns all card types"
              (let [response (mt/user-http-request :rasta :get 200 "ee/dependencies/graph/dependents"
                                                   :id dependency-card-id
                                                   :type "card"
                                                   :dependent-types "card")]
                (is (= 2 (count response)))
                (is (= #{"question" "model"} (set (map #(-> % :data :type) response))))))
            (testing "dependent-card-types ignored when dependent-types doesn't include card"
              (let [response (mt/user-http-request :rasta :get 200 "ee/dependencies/graph/dependents"
                                                   :id dependency-card-id
                                                   :type "card"
                                                   :dependent-types "dashboard"
                                                   :dependent-card-types "question")]
                (is (every? #(= "dashboard" (:type %)) response))))))))))

(deftest graph-archived-card-test
  (testing "GET /api/ee/dependencies/graph always includes archived upstream entities"
    (mt/with-premium-features #{:dependencies}
      (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus]
        (mt/with-temp [:model/User user {:email "[email protected]"}]
          (let [base-card (card/create-card! (basic-card "Archived Base Card") user)
                dependent-card (card/create-card! (wrap-card base-card) user)]
            (card/update-card! {:card-before-update base-card
                                :card-updates {:archived true}})
            (deps.test/synchronously-run-dependency-job!)
            (let [response (mt/user-http-request :rasta :get 200 "ee/dependencies/graph"
                                                 :id (:id dependent-card)
                                                 :type "card")
                  node-ids (set (map :id (:nodes response)))]
              (is (contains? node-ids (:id dependent-card)))
              (is (contains? node-ids (:id base-card)))
              (is (contains? node-ids (mt/id :orders))))))))))

(deftest graph-archived-upstream-edges-test
  (testing "GET /api/ee/dependencies/graph CONNECTS archived upstream entities with edges, not just nodes"
    ;; Chain: dependent-card (active) -> base-card (archived) -> orders (table).
    ;; The archived base-card is the *dependent* side of the base-card->orders edge, so a
    ;; downstream graph built with :include-archived-items :exclude drops that edge, leaving
    ;; the orders node present but disconnected. Asserts both edges survive.
    (mt/with-premium-features #{:dependencies}
      (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus]
        (mt/with-temp [:model/User user {:email "[email protected]"}]
          (let [base-card      (card/create-card! (basic-card "Archived Base Card") user)
                dependent-card (card/create-card! (wrap-card base-card) user)]
            (card/update-card! {:card-before-update base-card
                                :card-updates {:archived true}})
            (deps.test/synchronously-run-dependency-job!)
            (let [response (mt/user-http-request :rasta :get 200 "ee/dependencies/graph"
                                                 :id (:id dependent-card)
                                                 :type "card")
                  node-ids (set (map :id (:nodes response)))
                  edges    (:edges response)]
              (testing "archived upstream nodes are present"
                (is (contains? node-ids (:id base-card)))
                (is (contains? node-ids (mt/id :orders))))
              (testing "edge from active dependent to archived base card"
                (is (edge-present? edges "card" (:id dependent-card) "card" (:id base-card))))
              (testing "edge from archived base card to its upstream table is NOT dropped"
                (is (edge-present? edges "card" (:id base-card) "table" (mt/id :orders)))))))))))

(deftest dependents-archived-card-test
  (testing "GET /api/ee/dependencies/graph/dependents excludes archived dependents"
    (mt/with-premium-features #{:dependencies}
      (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus]
        (mt/with-temp [:model/User user {:email "[email protected]"}]
          (let [base-card (card/create-card! (basic-card "Base Card") user)
                dependent-card (card/create-card! (wrap-card base-card) user)]
            (card/update-card! {:card-before-update dependent-card
                                :card-updates {:archived true}})
            (deps.test/synchronously-run-dependency-job!)
            (let [response (mt/user-http-request :rasta :get 200 "ee/dependencies/graph/dependents"
                                                 :id (:id base-card)
                                                 :type "card"
                                                 :dependent-types "card")]
              (is (empty? response)))))))))

(deftest ^:synchronized dependents-inactive-table-test
  (testing "inactive tables are always included as dependents and in node counts"
    (mt/with-premium-features #{:dependencies :transforms-basic :hosting}
      (let [mp (mt/metadata-provider)
            products (lib.metadata/table mp (mt/id :products))]
        (mt/with-temp [:model/Table {table-id :id} {:db_id (mt/id)
                                                    :schema "PUBLIC"
                                                    :name "inactive_transform_table"
                                                    :active false}
                       :model/Transform {transform-id :id} {:name "Transform - inactivetabletest"
                                                            :source {:type :query
                                                                     :query (lib/query mp products)}
                                                            :target {:type   "table"
                                                                     :schema "PUBLIC"
                                                                     :name   "inactive_transform_table"}}]
          ;; Simulate the transform having been run: link it to its (now inactive) target table
          (t2/update! :model/Transform :id transform-id {:target_table_id table-id})
          (deps.hooks/after-transform-run transform-id table-id)
          (deps.test/synchronously-run-dependency-job!)
          (testing "GET /graph/dependents returns the inactive table as a child"
            (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/dependents"
                                                 :id transform-id
                                                 :type "transform")]
              (is (contains? (set (map :id response)) table-id))))
          (testing "GET /graph counts the inactive table in the transform's dependents_count"
            (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph"
                                                 :id transform-id
                                                 :type "transform")
                  transform-node (m/find-first #(and (= (:type %) "transform")
                                                     (= (:id %) transform-id))
                                               (:nodes response))]
              (is (= 1 (get-in transform-node [:dependents_count :table]))))))))))

(deftest ^:synchronized dependents-broken-parameter-test
  (testing "GET /api/ee/dependencies/graph/dependents?broken=true - only returns entities that are broken"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/User user {:email "[email protected]"}]
        (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus :model/AnalysisFinding :model/AnalysisFindingError]
          ;; Create cards in one metadata provider cache session
          (let [[model-card dependent-card] (lib-be/with-metadata-provider-cache
                                              (let [model-card (create-model-card! user "Model Card - brokentest")
                                                    dependent-card (create-dependent-card-on-model! user model-card "Dependent Card - brokentest")]
                                                [model-card dependent-card]))]
            ;; Run analysis in a fresh metadata provider cache session to detect the broken reference
            (lib-be/with-metadata-provider-cache
              (break-model-card! model-card)
              (let [next-card (create-dependent-card-on-model! user model-card "Another Dependent Card - brokentest" {:table :products})]
                (deps.test/synchronously-run-dependency-job!)
                (run-analysis-for-card! (:id next-card))
                (run-analysis-for-card! (:id dependent-card))
                (let [response2 (mt/user-http-request :crowberto :get 200 (str "ee/dependencies/graph/dependents?broken=true&type=card&id=" (:id model-card)))]
                  (is (= [(:id dependent-card)] (mapv :id response2))
                      "There should be one broken dependent"))
                (let [response2 (mt/user-http-request :crowberto :get 200 (str "ee/dependencies/graph/dependents?broken=false&type=card&id=" (:id model-card)))]
                  (is (= #{(:id dependent-card) (:id next-card)} (set (map :id response2)))
                      "There should two dependents total"))))))))))

(deftest ^:synchronized python-transform-not-broken-after-entity-check-test
  (testing "GHY-3584: a Python transform has no query to validate, so the entity-check task must not record it as broken"
    (mt/with-premium-features #{:dependencies}
      (mt/with-model-cleanup [:model/Dependency :model/DependencyStatus :model/AnalysisFinding :model/AnalysisFindingError]
        (mt/with-temp [:model/Transform {transform-id :id}
                       {:name   "Python transform - ghy3584"
                        :source {:type            :python
                                 :source-database (mt/id)
                                 :source-tables   [{:alias       "orders"
                                                    :database_id (mt/id)
                                                    :schema      "PUBLIC"
                                                    :table       "ORDERS"
                                                    :table_id    (mt/id :orders)}]
                                 :body            "def transform(orders):\n    return orders"}}]
          (deps.test/synchronously-run-dependency-job!)
          (deps.test/run-analysis-finding-job!)
          (let [dependent-ids (fn [broken?]
                                (set (map :id (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/dependents"
                                                                    :type "table"
                                                                    :id (mt/id :orders)
                                                                    :dependent-types "transform"
                                                                    :broken broken?))))]
            (is (contains? (dependent-ids false) transform-id)
                "the Python transform is a dependent of the table it reads")
            (is (not (contains? (dependent-ids true) transform-id))
                "the Python transform is not listed as broken")))))))

(deftest graph-permissions-test
  (testing "GET /api/ee/dependencies/graph requires read permissions on the starting entity"
    (mt/with-premium-features #{:dependencies}
      (mt/with-non-admin-groups-no-root-collection-perms
        (mt/with-temp [:model/Collection collection {}
                       :model/User user {:email "[email protected]"}]
          (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus]
            (let [card (card/create-card! (assoc (basic-card) :collection_id (u/the-id collection)) user)]
              (deps.test/synchronously-run-dependency-job!)
              (testing "Returns 403 when user lacks read permissions"
                (is (= "You don't have permissions to do that."
                       (mt/user-http-request :rasta :get 403 "ee/dependencies/graph"
                                             :id (:id card)
                                             :type "card"))))
              (testing "Returns 200 when user has read permissions"
                (perms/grant-collection-read-permissions! (perms/all-users-group) collection)
                (mt/user-http-request :rasta :get 200 "ee/dependencies/graph"
                                      :id (:id card)
                                      :type "card")))))))))

(deftest graph-dependents-permissions-test
  (testing "GET /api/ee/dependencies/graph/dependents requires read permissions on the starting entity"
    (mt/with-premium-features #{:dependencies}
      (mt/with-non-admin-groups-no-root-collection-perms
        (mt/with-temp [:model/Collection collection {}
                       :model/User user {:email "[email protected]"}]
          (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus]
            (let [{card-id :id} (card/create-card! (assoc (basic-card) :collection_id (:id collection)) user)]
              (deps.test/synchronously-run-dependency-job!)
              (testing "Returns 403 when user lacks read permissions"
                (is (= "You don't have permissions to do that."
                       (mt/user-http-request :rasta :get 403 "ee/dependencies/graph/dependents"
                                             :id card-id
                                             :type "card"
                                             :dependent-types "card"
                                             :dependent-card-types "question"))))
              (testing "Returns 200 when user has read permissions"
                (perms/grant-collection-read-permissions! (perms/all-users-group) collection)
                (mt/user-http-request :rasta :get 200 "ee/dependencies/graph/dependents"
                                      :id card-id
                                      :type "card"
                                      :dependent-types "card"
                                      :dependent-card-types "question")))))))))

(deftest graph-filtering-test
  (testing "GET /api/ee/dependencies/graph filters out upstream nodes the user cannot read"
    (mt/dataset test-data
      (mt/with-premium-features #{:dependencies}
        (mt/with-non-admin-groups-no-root-collection-perms
          (mt/with-temp [:model/Collection readable-collection {}
                         :model/Collection unreadable-collection {}
                         :model/User user {:email "[email protected]"}]
            (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus]
              (let [readable-base (card/create-card! (assoc (basic-card "Readable")
                                                            :collection_id (:id readable-collection)) user)
                    unreadable-base (card/create-card! (assoc (basic-card "Unreadable")
                                                              :collection_id (:id unreadable-collection)) user)
                    top-card (card/create-card! (assoc (wrap-two-cards readable-base unreadable-base)
                                                       :collection_id (:id readable-collection))
                                                user)]
                (deps.test/synchronously-run-dependency-job!)
                (perms/grant-collection-read-permissions! (perms/all-users-group) readable-collection)
                (testing "User sees complete upstream graph through readable path"
                  (let [response (mt/user-http-request :rasta :get 200 "ee/dependencies/graph"
                                                       :id (:id top-card)
                                                       :type "card")
                        nodes (set (map (juxt :type :id) (:nodes response)))
                        expected-nodes #{["card" (:id top-card)] ["card" (:id readable-base)] ["table" (mt/id :orders)]}]
                    (is (= expected-nodes nodes)
                        "Should see top-card, readable-base, and :orders table")))
                (testing "Edges show complete readable dependency chain"
                  (let [response (mt/user-http-request :rasta :get 200 "ee/dependencies/graph"
                                                       :id (:id top-card)
                                                       :type "card")
                        edges (set (:edges response))
                        expected-edges #{{:from_entity_id (:id top-card)
                                          :from_entity_type "card"
                                          :to_entity_id (:id readable-base)
                                          :to_entity_type "card"}
                                         {:from_entity_id (:id readable-base)
                                          :from_entity_type "card"
                                          :to_entity_id (mt/id :orders)
                                          :to_entity_type "table"}}]
                    (is (= expected-edges edges)
                        "Should have edges: top-card->readable-base and readable-base->orders")))))))))))

(deftest graph-dependents-filtering-test
  (testing "GET /api/ee/dependencies/graph/dependents filters out nodes the user cannot read"
    (mt/with-premium-features #{:dependencies}
      (mt/with-non-admin-groups-no-root-collection-perms
        (mt/with-temp [:model/Collection readable-collection {}
                       :model/Collection unreadable-collection {}
                       :model/User user {:email "[email protected]"}]
          (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus]
            (let [base-card (card/create-card! (assoc (basic-card) :collection_id (:id readable-collection)) user)
                  readable-dependent (card/create-card! (assoc (wrap-card base-card)
                                                               :collection_id (:id readable-collection))
                                                        user)
                  unreadable-dependent (card/create-card! (assoc (wrap-card base-card)
                                                                 :collection_id (:id unreadable-collection))
                                                          user)]
              (deps.test/synchronously-run-dependency-job!)
              (perms/grant-collection-read-permissions! (perms/all-users-group) readable-collection)
              (testing "User sees only readable dependents"
                (let [response (mt/user-http-request :rasta :get 200 "ee/dependencies/graph/dependents"
                                                     :id (:id base-card)
                                                     :type "card"
                                                     :dependent-types "card"
                                                     :dependent-card-types "question")
                      dependent-ids (set (map :id response))]
                  (is (contains? dependent-ids (:id readable-dependent)))
                  (is (not (contains? dependent-ids (:id unreadable-dependent)))))))))))))

(deftest graph-multi-level-filtering-test
  (testing "GET /api/ee/dependencies/graph includes upstream nodes if ANY path to them is readable"
    (mt/dataset test-data
      (mt/with-premium-features #{:dependencies}
        (mt/with-empty-h2-app-db!
          (mt/with-non-admin-groups-no-root-collection-perms
            (mt/with-temp [:model/Collection readable-collection {}
                           :model/Collection unreadable-collection {}
                           :model/User user {:email "[email protected]"}]
              (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus]
                (let [base-card (card/create-card! (assoc (basic-card) :collection_id (:id readable-collection)) user)
                      unreadable-middle (card/create-card! (assoc (wrap-card base-card)
                                                                  :collection_id (:id unreadable-collection))
                                                           user)
                      readable-alternate (card/create-card! (assoc (wrap-card base-card)
                                                                   :collection_id (:id readable-collection))
                                                            user)
                      end-card (card/create-card! (assoc (wrap-two-cards unreadable-middle readable-alternate)
                                                         :collection_id (:id readable-collection))
                                                  user)]
                  (deps.test/synchronously-run-dependency-job!)
                  (perms/grant-collection-read-permissions! (perms/all-users-group) readable-collection)
                  (testing "Diamond pattern: complete upstream graph via readable path"
                    (let [response (mt/user-http-request :rasta :get 200 "ee/dependencies/graph"
                                                         :id (:id end-card)
                                                         :type "card")
                          nodes (set (map (juxt :type :id) (:nodes response)))
                          expected-nodes #{["card" (:id end-card)] ["card" (:id readable-alternate)]
                                           ["card" (:id base-card)] ["table" (mt/id :orders)]}]
                      (is (= expected-nodes nodes)
                          "Should see end-card, readable-alternate, base-card, and :orders table")))
                  (testing "Edges show complete readable dependency chain"
                    (let [response (mt/user-http-request :rasta :get 200 "ee/dependencies/graph"
                                                         :id (:id end-card)
                                                         :type "card")
                          edges (set (:edges response))
                          expected-edges #{{:from_entity_id (:id end-card)
                                            :from_entity_type "card"
                                            :to_entity_id (:id readable-alternate)
                                            :to_entity_type "card"}
                                           {:from_entity_id (:id readable-alternate)
                                            :from_entity_type "card"
                                            :to_entity_id (:id base-card)
                                            :to_entity_type "card"}
                                           {:from_entity_id (:id base-card)
                                            :from_entity_type "card"
                                            :to_entity_id (mt/id :orders)
                                            :to_entity_type "table"}}]
                      (is (= expected-edges edges)
                          "Should have edges through readable path only"))))))))))))

(deftest graph-filtering-all-unreadable-test
  (testing "GET /api/ee/dependencies/graph returns only root node when all upstream dependencies are unreadable"
    (mt/dataset test-data
      (mt/with-premium-features #{:dependencies}
        (mt/with-non-admin-groups-no-root-collection-perms
          (mt/with-temp [:model/Collection readable-collection {}
                         :model/Collection unreadable-collection {}
                         :model/User user {:email "[email protected]"}]
            (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus]
              (let [unreadable-base (card/create-card! (assoc (basic-card "Unreadable")
                                                              :collection_id (:id unreadable-collection)) user)
                    top-card (card/create-card! (assoc (wrap-card unreadable-base)
                                                       :collection_id (:id readable-collection))
                                                user)]
                (deps.test/synchronously-run-dependency-job!)
                (perms/grant-collection-read-permissions! (perms/all-users-group) readable-collection)
                (testing "User sees only the top card in the graph"
                  (let [response (mt/user-http-request :rasta :get 200 "ee/dependencies/graph"
                                                       :id (:id top-card)
                                                       :type "card")
                        nodes (set (map (juxt :type :id) (:nodes response)))]
                    (is (= #{["card" (:id top-card)]} nodes)
                        "Should see only top-card when all dependencies are unreadable")))
                (testing "No edges when all dependencies are filtered"
                  (let [response (mt/user-http-request :rasta :get 200 "ee/dependencies/graph"
                                                       :id (:id top-card)
                                                       :type "card")]
                    (is (empty? (:edges response))
                        "Should have no edges when all dependencies are filtered out")))))))))))

(deftest graph-snippet-filtering-test
  (testing "GET /api/ee/dependencies/graph/dependents filters snippet dependents based on card permissions"
    (mt/dataset test-data
      (mt/with-premium-features #{:dependencies}
        (mt/with-non-admin-groups-no-root-collection-perms
          (mt/with-temp [:model/Collection readable-collection {}
                         :model/Collection unreadable-collection {}
                         :model/User user {:email "[email protected]"}
                         :model/NativeQuerySnippet {snippet-id :id snippet-name :name} {:name "test-snippet"
                                                                                        :content "WHERE ID > 10"}]
            (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus]
              (let [tag-name (str "snippet: " snippet-name)
                    mp (mt/metadata-provider)
                    native-query (fn []
                                   (-> (lib/native-query mp (format "SELECT * FROM ORDERS %s" (str "{{" tag-name "}}")))
                                       (lib/with-template-tags {tag-name {:name tag-name
                                                                          :display-name (str "Snippet: " snippet-name)
                                                                          :type :snippet
                                                                          :snippet-name snippet-name
                                                                          :snippet-id snippet-id}})))
                    readable-card (card/create-card! {:name "Readable card with snippet"
                                                      :dataset_query (native-query)
                                                      :display :table
                                                      :visualization_settings {}
                                                      :collection_id (:id readable-collection)}
                                                     user)
                    unreadable-card (card/create-card! {:name "Unreadable card with snippet"
                                                        :dataset_query (native-query)
                                                        :display :table
                                                        :visualization_settings {}
                                                        :collection_id (:id unreadable-collection)}
                                                       user)]
                (deps.test/synchronously-run-dependency-job!)
                (perms/grant-collection-read-permissions! (perms/all-users-group) readable-collection)
                (testing "User sees only readable cards as dependents of the snippet"
                  (let [response (mt/user-http-request :rasta :get 200 "ee/dependencies/graph/dependents"
                                                       :id snippet-id
                                                       :type "snippet"
                                                       :dependent-types "card"
                                                       :dependent-card-types "question")
                        dependent-ids (set (map :id response))]
                    (is (contains? dependent-ids (:id readable-card))
                        "Should see readable card as dependent")
                    (is (not (contains? dependent-ids (:id unreadable-card)))
                        "Should not see unreadable card as dependent")))
                (testing "User sees a root snippet with the snippets root permission, not the default root one"
                  (mt/with-non-admin-groups-no-root-collection-for-namespace-perms collection/snippets-ns
                    (let [snippet-node? (fn []
                                          (contains? (->> (mt/user-http-request :rasta :get 200 "ee/dependencies/graph"
                                                                                :id (:id readable-card)
                                                                                :type "card")
                                                          :nodes
                                                          (map (juxt :type :id))
                                                          set)
                                                     ["snippet" snippet-id]))]
                      (perms/grant-collection-read-permissions! (perms/all-users-group) collection/root-collection)
                      (is (not (snippet-node?)))
                      (perms/revoke-collection-permissions! (perms/all-users-group) collection/root-collection)
                      (perms/grant-collection-read-permissions! (perms/all-users-group)
                                                                (assoc collection/root-collection :namespace collection/snippets-ns))
                      (is (snippet-node?)))))))))))))

(deftest graph-table-permission-filtering-test
  (testing "GET /api/ee/dependencies/graph filters out tables when user lacks table permissions"
    (mt/dataset test-data
      (mt/with-premium-features #{:dependencies}
        (mt/with-non-admin-groups-no-root-collection-perms
          (mt/with-temp [:model/Collection readable-collection {}
                         :model/User user {:email "[email protected]"}]
            (mt/with-temp-copy-of-db
              (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus]
                (mt/with-no-data-perms-for-all-users!
                  (perms/set-table-permission! (perms/all-users-group) (mt/id :orders) :perms/view-data :blocked)
                  (perms/set-table-permission! (perms/all-users-group) (mt/id :orders) :perms/create-queries :no)
                  (let [card (card/create-card! (assoc (basic-card "Card on orders")
                                                       :collection_id (:id readable-collection)) user)]
                    (deps.test/synchronously-run-dependency-job!)
                    (perms/grant-collection-read-permissions! (perms/all-users-group) readable-collection)
                    (testing "User sees only the card, table is filtered out"
                      (let [response (mt/user-http-request :rasta :get 200 "ee/dependencies/graph"
                                                           :id (:id card)
                                                           :type "card")
                            nodes (set (map (juxt :type :id) (:nodes response)))]
                        (is (= #{["card" (:id card)]} nodes)
                            "Should see only the card, not the unreadable table")))
                    (testing "No edges when table is filtered"
                      (let [response (mt/user-http-request :rasta :get 200 "ee/dependencies/graph"
                                                           :id (:id card)
                                                           :type "card")]
                        (is (empty? (:edges response))
                            "Should have no edges when table is filtered out")))))))))))))

(deftest graph-returns-dashboard-for-cards-test
  (testing "Graph endpoints return dashboard data for cards in dashboards"
    (mt/with-premium-features #{:dependencies}
      (mt/with-current-user (mt/user->id :rasta)
        (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus]
          (mt/with-temp [:model/User user {:email "[email protected]"}
                         :model/Dashboard dashboard {:name "Test Dashboard"}]
            (let [base-card (card/create-card! (basic-card "Base Card") user)
                  dashboard-card (card/create-card! (assoc (wrap-card base-card)
                                                           :dashboard_id (:id dashboard))
                                                    user)]
              (deps.test/synchronously-run-dependency-job!)
              (testing "GET /api/ee/dependencies/graph returns dashboard with :id and :name"
                (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph"
                                                     :id (:id dashboard-card)
                                                     :type :card)
                      card-node (first (filter #(= (:id %) (:id dashboard-card)) (:nodes response)))]
                  (is (= {:id (:id dashboard) :name "Test Dashboard"}
                         (get-in card-node [:data :dashboard])))
                  (is (= (:id dashboard)
                         (get-in card-node [:data :dashboard_id])))))
              (testing "GET /api/ee/dependencies/graph/dependents returns dashboard with :id and :name"
                (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/dependents"
                                                     :id (:id base-card)
                                                     :type :card
                                                     :dependent-types :card
                                                     :dependent-card-types :question)
                      card-node (first (filter #(= (:id %) (:id dashboard-card)) response))]
                  (is (some? card-node))
                  (is (= {:id (:id dashboard) :name "Test Dashboard"}
                         (get-in card-node [:data :dashboard])))
                  (is (= (:id dashboard)
                         (get-in card-node [:data :dashboard_id]))))))))))))

(deftest graph-returns-document-for-cards-test
  (testing "Graph endpoints return document data for cards in documents"
    (mt/with-premium-features #{:dependencies}
      (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus]
        (mt/with-temp [:model/User user {:email "[email protected]"}
                       :model/Document document {:name "Test Document"}]
          (let [base-card (card/create-card! (basic-card "Base Card") user)
                document-card (card/create-card! (assoc (wrap-card base-card)
                                                        :document_id (:id document))
                                                 user)]
            (deps.test/synchronously-run-dependency-job!)
            (testing "GET /api/ee/dependencies/graph returns document with :id and :name"
              (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph"
                                                   :id (:id document-card)
                                                   :type :card)
                    card-node (first (filter #(= (:id %) (:id document-card)) (:nodes response)))]
                (is (= {:id (:id document) :name "Test Document"}
                       (get-in card-node [:data :document])))
                (is (= (:id document)
                       (get-in card-node [:data :document_id])))))
            (testing "GET /api/ee/dependencies/graph/dependents returns document with :id and :name"
              (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/dependents"
                                                   :id (:id base-card)
                                                   :type :card
                                                   :dependent-types :card
                                                   :dependent-card-types :question)
                    card-node (first (filter #(= (:id %) (:id document-card)) response))]
                (is (some? card-node))
                (is (= {:id (:id document) :name "Test Document"}
                       (get-in card-node [:data :document])))
                (is (= (:id document)
                       (get-in card-node [:data :document_id])))))))))))

(deftest graph-segment-root-test
  (testing "GET /api/ee/dependencies/graph with segment as root node"
    (mt/with-test-user :crowberto
      (mt/with-premium-features #{:dependencies}
        (let [products-id (mt/id :products)
              price-field-id (mt/id :products :price)]
          (mt/with-temp [:model/Segment {segment-id :id :as segment} {:name "High Value Products"
                                                                      :table_id products-id
                                                                      :definition {:filter [:> [:field price-field-id nil] 50]}}]
            (events/publish-event! :event/segment-create {:object segment :user-id (mt/user->id :crowberto)})
            (deps.test/synchronously-run-dependency-job!)
            (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph"
                                                 :id segment-id
                                                 :type "segment")
                  node-types (set (map :type (:nodes response)))]
              (testing "returns segment and table nodes"
                (is (contains? node-types "segment"))
                (is (contains? node-types "table")))
              (testing "segment node has correct data"
                (let [segment-node (first (filter #(= (:type %) "segment") (:nodes response)))]
                  (is (= segment-id (:id segment-node))))))))))))

(deftest graph-segment-dependents-test
  (testing "GET /api/ee/dependencies/graph/dependents with segment"
    (mt/with-premium-features #{:dependencies}
      (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus]
        (let [products-id (mt/id :products)
              price-field-id (mt/id :products :price)]
          (mt/with-temp [:model/Segment {segment-id :id :as segment} {:name "High Value Products"
                                                                      :table_id products-id
                                                                      :definition {:filter [:> [:field price-field-id nil] 50]}}
                         :model/User user {:email "[email protected]"}]
            (mt/with-test-user :crowberto
              (events/publish-event! :event/segment-create {:object segment :user-id (mt/user->id :crowberto)}))
            (let [mp (mt/metadata-provider)
                  products (lib.metadata/table mp products-id)
                  query-with-segment (-> (lib/query mp products)
                                         (lib/filter (lib.metadata/segment mp segment-id)))
                  card (card/create-card! (card-with-query "Card using segment" query-with-segment) user)
                  _ (deps.test/synchronously-run-dependency-job!)
                  response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/dependents"
                                                 :id segment-id
                                                 :type "segment"
                                                 :dependent-types "card"
                                                 :dependent-card-types "question")]
              (testing "returns card that uses the segment"
                (is (= 1 (count response)))
                (is (= (:id card) (:id (first response))))))))))))

(deftest graph-action-dependents-test
  (testing "GET /api/ee/dependencies/graph/dependents returns the actions a user can read"
    (mt/with-premium-features #{:dependencies}
      (mt/with-non-admin-groups-no-root-collection-perms
        (mt/with-temp [:model/Collection readable-collection   {}
                       :model/Collection unreadable-collection {:namespace "data-actions"}
                       :model/Card {model-id :id} (assoc (basic-card "Venues model" :venues)
                                                         :type          :model
                                                         :collection_id (:id readable-collection))
                       :model/Action {readable-id :id} {:type     :implicit
                                                        :name     "Create venue"
                                                        :model_id model-id}
                       :model/ImplicitAction _ {:action_id readable-id, :kind "row/create"}
                       :model/Action {unreadable-id :id} {:type          :query
                                                          :name          "Delete venue"
                                                          :collection_id (:id unreadable-collection)}
                       :model/Action {root-id :id} {:type :query
                                                    :name "Archive venue"}
                       :model/QueryAction _ {:action_id     root-id
                                             :database_id   (mt/id)
                                             :dataset_query (-> (lib/native-query (mt/metadata-provider)
                                                                                  (str "DELETE FROM venues WHERE id IN "
                                                                                       "(SELECT id FROM {{#" model-id "}})"))
                                                                (lib/with-template-tags
                                                                  {(str "#" model-id) {:id           "model-tag"
                                                                                       :type         :card
                                                                                       :name         (str "#" model-id)
                                                                                       :display-name "Venues model"
                                                                                       :card-id      model-id}}))}
                       :model/QueryAction _ {:action_id     unreadable-id
                                             :database_id   (mt/id)
                                             :dataset_query (-> (lib/native-query (mt/metadata-provider)
                                                                                  (str "DELETE FROM venues WHERE id IN "
                                                                                       "(SELECT id FROM {{#" model-id "}})"))
                                                                (lib/with-template-tags
                                                                  {(str "#" model-id) {:id           "model-tag"
                                                                                       :type         :card
                                                                                       :name         (str "#" model-id)
                                                                                       :display-name "Venues model"
                                                                                       :card-id      model-id}}))}]
          (mt/with-model-cleanup [:model/Dependency :model/DependencyStatus]
            (perms/grant-collection-read-permissions! (perms/all-users-group) readable-collection)
            (deps.test/synchronously-run-dependency-job!)
            (let [dependents (fn [user]
                               (->> (mt/user-http-request user :get 200 "ee/dependencies/graph/dependents"
                                                          :id model-id
                                                          :type "card"
                                                          :dependent-types "action")
                                    (map (juxt :type :id (comp :name :data) (comp (juxt :name :namespace) :collection :data)))
                                    set))]
              (is (= #{["action" readable-id "Create venue" [(:name readable-collection) nil]]
                       ["action" unreadable-id "Delete venue" [(:name unreadable-collection) "data-actions"]]
                       ["action" root-id "Archive venue" ["Data actions" "data-actions"]]}
                     (dependents :crowberto)))
              (is (= #{["action" readable-id "Create venue" [(:name readable-collection) nil]]}
                     (dependents :rasta))))))))))

(deftest implicit-action-table-change-moves-its-dependency-test
  (testing "changing the table of an implicit action without a model moves its dependency to the new table"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/Action {action-id :id} {:type :implicit, :name "Create venue"}
                     :model/ImplicitAction _ {:action_id action-id, :kind "row/create", :table_id (mt/id :venues)}]
        (mt/with-model-cleanup [:model/Dependency :model/DependencyStatus]
          (let [dependents (fn [table-key]
                             (->> (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/dependents"
                                                        :id (mt/id table-key)
                                                        :type "table"
                                                        :dependent-types "action")
                                  (map :id)
                                  set))]
            (deps.test/synchronously-run-dependency-job!)
            (is (contains? (dependents :venues) action-id))
            (t2/update! :model/ImplicitAction {:action_id action-id} {:table_id (mt/id :categories)})
            (deps.test/synchronously-run-dependency-job!)
            (is (contains? (dependents :categories) action-id))
            (is (not (contains? (dependents :venues) action-id)))))))))

(deftest graph-measure-root-test
  (testing "GET /api/ee/dependencies/graph with measure as root node"
    (mt/with-test-user :crowberto
      (mt/with-premium-features #{:dependencies}
        (let [mp (mt/metadata-provider)
              products-id (mt/id :products)
              products (lib.metadata/table mp products-id)
              price (lib.metadata/field mp (mt/id :products :price))]
          (mt/with-temp [:model/Measure {measure-id :id :as measure} {:name "Total Price"
                                                                      :table_id products-id
                                                                      :definition (-> (lib/query mp products)
                                                                                      (lib/aggregate (lib/sum price)))}]
            (events/publish-event! :event/measure-create {:object measure :user-id (mt/user->id :crowberto)})
            (deps.test/synchronously-run-dependency-job!)
            (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph"
                                                 :id measure-id
                                                 :type "measure")
                  node-types (set (map :type (:nodes response)))]
              (testing "returns measure and table nodes"
                (is (contains? node-types "measure"))
                (is (contains? node-types "table")))
              (testing "measure node has correct data"
                (let [measure-node (first (filter #(= (:type %) "measure") (:nodes response)))]
                  (is (= measure-id (:id measure-node))))))))))))

(deftest graph-measure-with-measure-dependency-test
  (testing "GET /api/ee/dependencies/graph with measure depending on another measure"
    (mt/with-test-user :crowberto
      (mt/with-premium-features #{:dependencies}
        (let [mp (mt/metadata-provider)
              products-id (mt/id :products)
              products (lib.metadata/table mp products-id)
              price (lib.metadata/field mp (mt/id :products :price))
              rating (lib.metadata/field mp (mt/id :products :rating))]
          (mt/with-temp [:model/Measure {measure-a-id :id :as measure-a} {:name "Measure A"
                                                                          :table_id products-id
                                                                          :definition (-> (lib/query mp products)
                                                                                          (lib/aggregate (lib/sum price)))}]
            (events/publish-event! :event/measure-create {:object measure-a :user-id (mt/user->id :crowberto)})
            (deps.test/synchronously-run-dependency-job!)
            (let [mp' (mt/metadata-provider)]
              (mt/with-temp [:model/Measure {measure-b-id :id :as measure-b} {:name "Measure B"
                                                                              :table_id products-id
                                                                              :definition (-> (lib/query mp' products)
                                                                                              (lib/aggregate (lib/+ (lib.metadata/measure mp' measure-a-id)
                                                                                                                    (lib/sum rating))))}]
                (events/publish-event! :event/measure-create {:object measure-b :user-id (mt/user->id :crowberto)})
                (deps.test/synchronously-run-dependency-job!)
                (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph"
                                                     :id measure-b-id
                                                     :type "measure")
                      node-ids (set (map :id (:nodes response)))
                      node-types (set (map :type (:nodes response)))]
                  (testing "returns both measures and table"
                    (is (contains? node-ids measure-a-id))
                    (is (contains? node-ids measure-b-id))
                    (is (contains? node-types "table")))
                  (testing "edges show measure-b depends on measure-a"
                    (is (some #(and (= (:from_entity_type %) "measure")
                                    (= (:from_entity_id %) measure-b-id)
                                    (= (:to_entity_type %) "measure")
                                    (= (:to_entity_id %) measure-a-id))
                              (:edges response)))))))))))))

(deftest graph-measure-dependents-test
  (testing "GET /api/ee/dependencies/graph/dependents with measure"
    (mt/with-premium-features #{:dependencies}
      (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus]
        (let [mp (mt/metadata-provider)
              products-id (mt/id :products)
              products (lib.metadata/table mp products-id)
              price (lib.metadata/field mp (mt/id :products :price))]
          (mt/with-temp [:model/Measure {measure-id :id :as measure} {:name "Total Price"
                                                                      :table_id products-id
                                                                      :definition (-> (lib/query mp products)
                                                                                      (lib/aggregate (lib/sum price)))}
                         :model/User user {:email "[email protected]"}]
            (mt/with-test-user :crowberto
              (events/publish-event! :event/measure-create {:object measure :user-id (mt/user->id :crowberto)}))
            (let [mp' (mt/metadata-provider)
                  query-with-measure (-> (lib/query mp' products)
                                         (lib/aggregate (lib.metadata/measure mp' measure-id)))
                  card (card/create-card! (card-with-query "Card using measure" query-with-measure) user)
                  _ (deps.test/synchronously-run-dependency-job!)
                  response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/dependents"
                                                 :id measure-id
                                                 :type "measure"
                                                 :dependent-types "card"
                                                 :dependent-card-types "question")]
              (testing "returns card that uses the measure"
                (is (= 1 (count response)))
                (is (= (:id card) (:id (first response))))))))))))

;; TODO (AlexP 01/15/26) -- fix and unskip this test
#_(deftest ^:synchronized graph-archived-measure-in-chain-test
    (testing "GET /api/ee/dependencies/graph when a measure in the chain is archived"
      (mt/with-premium-features #{:dependencies}
        (mt/with-model-cleanup [:model/Measure]
          (let [mp (mt/metadata-provider)
                products-id (mt/id :products)
                products (lib.metadata/table mp products-id)
                price (lib.metadata/field mp (mt/id :products :price))
                ;; Create measure A (base measure) via API
                {measure-a-id :id} (mt/user-http-request :crowberto :post 200 "measure"
                                                         {:name "Measure A"
                                                          :definition (-> (lib/query mp products)
                                                                          (lib/aggregate (lib/sum price)))})
                mp' (mt/metadata-provider)
                ;; Create measure B that depends on measure A
                {measure-b-id :id} (mt/user-http-request :crowberto :post 200 "measure"
                                                         {:name "Measure B"
                                                          :definition (-> (lib/query mp' products)
                                                                          (lib/aggregate (lib/* (lib.metadata/measure mp' measure-a-id)
                                                                                                2)))})
                mp'' (mt/metadata-provider)
                ;; Create measure C that depends on measure B
                {measure-c-id :id} (mt/user-http-request :crowberto :post 200 "measure"
                                                         {:name "Measure C"
                                                          :definition (-> (lib/query mp'' products)
                                                                          (lib/aggregate (lib/+ (lib.metadata/measure mp'' measure-b-id)
                                                                                                100)))})]
            (testing "before archiving, all three measures appear in the dependency graph"
              (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph"
                                                   :id measure-c-id
                                                   :type "measure")
                    node-ids (set (map :id (:nodes response)))
                    edges (:edges response)]
                (is (contains? node-ids measure-a-id))
                (is (contains? node-ids measure-b-id))
                (is (contains? node-ids measure-c-id))
                (is (contains? node-ids products-id))
                ;; Verify the edge from B to A exists
                (is (some #(and (= (:from_entity_type %) "measure")
                                (= (:from_entity_id %) measure-b-id)
                                (= (:to_entity_type %) "measure")
                                (= (:to_entity_id %) measure-a-id))
                          edges)
                    "Edge from B to A should exist")))
            ;; Archive measure B (the middle of the chain)
            (mt/user-http-request :crowberto :put 200 (str "measure/" measure-b-id)
                                  {:archived true :revision_message "Archive middle measure"})
            (deps.test/synchronously-run-dependency-job!)
            (testing "after archiving measure B, it and measure A are excluded (chain broken)"
              (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph"
                                                   :id measure-c-id
                                                   :type "measure")
                    node-ids (set (map :id (:nodes response)))]
                (is (contains? node-ids measure-c-id) "measure C should still appear")
                (is (not (contains? node-ids measure-b-id)) "archived measure B should be excluded")
                (is (not (contains? node-ids measure-a-id)) "measure A should be excluded (unreachable)")
                ;; products table still appears because measure C has a direct dependency on it
                (is (contains? node-ids products-id) "products table still appears (direct dep from C)")))
            (testing "with archived=true, the full chain is visible again"
              (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph"
                                                   :id measure-c-id
                                                   :type "measure"
                                                   :archived true)
                    node-ids (set (map :id (:nodes response)))]
                (is (contains? node-ids measure-a-id) "measure A should appear with archived=true")
                (is (contains? node-ids measure-b-id) "measure B should appear with archived=true")
                (is (contains? node-ids measure-c-id) "measure C should appear")
                (is (contains? node-ids products-id) "products table should appear"))))))))

(deftest ^:synchronized graph-view-count-test
  (testing "GET /api/ee/dependencies/graph should return :view_count for :card"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/User {user-id :id} {}
                     :model/Card {card-id :id} {}]
        (events/publish-event! :event/card-read {:object-id card-id :user-id user-id :context :question})
        (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph"
                                             :id card-id
                                             :type "card")]
          (is (=? {:nodes [{:id card-id
                            :data {:view_count 1}}]}
                  response))))))
  (testing "GET /api/ee/dependencies/graph should return :view_count for :dashboard"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/User      {user-id :id}      {}
                     :model/Dashboard {dashboard-id :id} {}]
        (events/publish-event! :event/dashboard-read {:object-id dashboard-id :user-id user-id})
        (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph"
                                             :id dashboard-id
                                             :type "dashboard")]
          (is (=? {:nodes [{:id dashboard-id
                            :data {:view_count 1}}]}
                  response))))))
  (testing "GET /api/ee/dependencies/graph should return :view_count for :document"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/User     {user-id :id}      {}
                     :model/Document {document-id :id} {}]
        (events/publish-event! :event/document-read {:object-id document-id :user-id user-id})
        (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph"
                                             :id document-id
                                             :type "document")]
          (is (=? {:nodes [{:id document-id
                            :data {:view_count 1}}]}
                  response)))))))

(deftest ^:synchronized unreferenced-questions-test
  (testing "GET /api/ee/dependencies/unreferenced - only unreferenced questions are returned"
    (mt/with-premium-features #{:dependencies}
      (let [mp (mt/metadata-provider)
            products (lib.metadata/table mp (mt/id :products))]
        (mt/with-temp [:model/Card {referenced-card-id :id} {:name "Referenced Card - unreftest"
                                                             :type :question
                                                             :dataset_query (lib/query mp products)}
                       :model/Card {unreffed-card-id :id} {:name "Unreferenced Card - unreftest"
                                                           :type :question
                                                           :dataset_query (->> referenced-card-id
                                                                               (lib.metadata/card mp)
                                                                               (lib/query mp))}]
          (events/publish-event! :event/card-create {:object (t2/select-one :model/Card :id referenced-card-id) :user-id (mt/user->id :crowberto)})
          (events/publish-event! :event/card-create {:object (t2/select-one :model/Card :id unreffed-card-id) :user-id (mt/user->id :crowberto)})
          (deps.test/synchronously-run-dependency-job!)
          (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/unreferenced?types=card&card-types=question&query=unreftest")]
            (is (=? {:data [{:id unreffed-card-id
                             :type "card"
                             :data {:name "Unreferenced Card - unreftest"}}]}
                    response))))))))

(deftest ^:synchronized unreferenced-tables-test
  (testing "GET /api/ee/dependencies/unreferenced - only unreferenced tables are returned"
    (mt/with-premium-features #{:dependencies}
      (let [mp (mt/metadata-provider)]
        (mt/with-temp [:model/Table {unreffed-table-id :id} {:name "Unreferenced Table - unreftest"}
                       :model/Table {referenced-table-id :id} {:name "Referenced Table - unreftest"}
                       :model/Card {card-id :id} {:name "Referencing Card"
                                                  :type :question
                                                  :dataset_query (lib/query mp (lib.metadata/table mp referenced-table-id))}]
          (events/publish-event! :event/card-create {:object (t2/select-one :model/Card :id card-id) :user-id (mt/user->id :crowberto)})
          (deps.test/synchronously-run-dependency-job!)
          (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/unreferenced?types=table&query=unreftest")]
            (is (=? {:data [{:id unreffed-table-id
                             :type "table"
                             :data {:name "Unreferenced Table - unreftest"}}]}
                    response))))))))

(deftest ^:synchronized unreferenced-transforms-test
  (testing "GET /api/ee/dependencies/unreferenced - only unreferenced transforms are returned"
    (mt/with-premium-features #{:dependencies}
      (let [mp (mt/metadata-provider)
            products (lib.metadata/table mp (mt/id :products))]
        (mt/with-temp [:model/Table     {referenced-table-id :id} {:db_id  (mt/id)
                                                                   :schema "PUBLIC"
                                                                   :name   "referenced_transform_table"
                                                                   :active true}
                       :model/Transform {unreffed-transform-id :id} {:name "Unreferenced Transform - unreftest"
                                                                     :source {:type :query
                                                                              :query (lib/query mp products)}
                                                                     :target {:type   "table"
                                                                              :schema "PUBLIC"
                                                                              :name   "unreferenced_transform_table"}}
                       :model/Transform {referenced-transform-id :id} {:name "Referenced Transform - unreftest"
                                                                       :source {:type :query
                                                                                :query (lib/query mp products)}
                                                                       :target {:type   "table"
                                                                                :schema "PUBLIC"
                                                                                :name   "referenced_transform_table"}}]
          ;; Simulate the referenced transform having been run: link it to its target table
          ;; so the table→transform dep is visible in the dependency graph.
          (t2/update! :model/Transform :id referenced-transform-id {:target_table_id referenced-table-id})
          (deps.hooks/after-transform-run referenced-transform-id referenced-table-id)
          (deps.test/synchronously-run-dependency-job!)
          (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/unreferenced?types=transform&query=unreftest")]
            (is (=? {:data [{:id unreffed-transform-id
                             :type "transform"
                             :data {:name "Unreferenced Transform - unreftest"}}]}
                    response))))))))

(deftest ^:synchronized unreferenced-snippets-test
  (testing "GET /api/ee/dependencies/unreferenced - only unreferenced snippets are returned"
    (mt/with-premium-features #{:dependencies}
      (let [mp (mt/metadata-provider)]
        (mt/with-temp [:model/NativeQuerySnippet {unreffed-snippet-id :id} {:name "Unreferenced Snippet - unreftest"
                                                                            :content "WHERE ID > 10"}
                       :model/NativeQuerySnippet {referenced-snippet-id :id snippet-name :name} {:name "Referenced Snippet - unreftest"
                                                                                                 :content "WHERE ID > 20"}]
          (let [tag-name (str "snippet: " snippet-name)
                native-query (-> (lib/native-query mp (format "SELECT * FROM PRODUCTS %s" (str "{{" tag-name "}}")))
                                 (lib/with-template-tags {tag-name {:name tag-name
                                                                    :display-name (str "Snippet: " snippet-name)
                                                                    :type :snippet
                                                                    :snippet-name snippet-name
                                                                    :snippet-id referenced-snippet-id}}))]
            (mt/with-temp [:model/Card {card-id :id} {:name "Card using snippet"
                                                      :type :question
                                                      :dataset_query native-query}]
              (events/publish-event! :event/card-create {:object (t2/select-one :model/Card :id card-id) :user-id (mt/user->id :crowberto)})
              (deps.test/synchronously-run-dependency-job!)
              (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/unreferenced?types=snippet&query=unreftest")]
                (is (=? {:data   [{:id unreffed-snippet-id
                                   :type "snippet"
                                   :data {:name "Unreferenced Snippet - unreftest"}}]}
                        response))))))))))

(deftest ^:synchronized unreferenced-dashboards-test
  (testing "GET /api/ee/dependencies/unreferenced - only unreferenced dashboards are returned"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/Dashboard {unreffed-dashboard-id :id} {:name "Unreferenced Dashboard - unreftest"}
                     :model/Dashboard {referenced-dashboard-id :id} {:name "Referenced Dashboard - unreftest"}
                     :model/Document {document-id :id} {:name "Document with dashboard link"
                                                        :document {:type "doc"
                                                                   :content [{:type "paragraph"
                                                                              :content [{:type "smartLink"
                                                                                         :attrs {"entityId" referenced-dashboard-id
                                                                                                 "model" "dashboard"}}]}]}
                                                        :content_type "application/json+vnd.prose-mirror"}]
        (events/publish-event! :event/document-create {:object (t2/select-one :model/Document :id document-id) :user-id (mt/user->id :crowberto)})
        (deps.test/synchronously-run-dependency-job!)
        (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/unreferenced?types=dashboard&query=unreftest")]
          (is (=? {:data [{:id unreffed-dashboard-id
                           :type "dashboard"
                           :data {:name "Unreferenced Dashboard - unreftest"}}]}
                  response)))))))

(deftest ^:synchronized unreferenced-documents-test
  (testing "GET /api/ee/dependencies/unreferenced - only unreferenced documents are returned"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/Document {referenced-document-id :id} {:name "Referenced Document - unreftest"}
                     :model/Document {unreffed-document-id :id} {:name "Unreferenced Document - unreftest"
                                                                 :document {:type "doc"
                                                                            :content [{:type "paragraph"
                                                                                       :content [{:type "smartLink"
                                                                                                  :attrs {"entityId" referenced-document-id
                                                                                                          "model" "document"}}]}]}
                                                                 :content_type "application/json+vnd.prose-mirror"}]
        (events/publish-event! :event/document-create {:object (t2/select-one :model/Document :id unreffed-document-id) :user-id (mt/user->id :crowberto)})
        (deps.test/synchronously-run-dependency-job!)
        (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/unreferenced?types=document&query=unreftest")]
          (is (=? {:data [{:id unreffed-document-id
                           :type "document"
                           :data {:name "Unreferenced Document - unreftest"}}]}
                  response)))))))

(deftest ^:synchronized unreferenced-sandboxes-test
  (testing "GET /api/ee/dependencies/unreferenced - unreferenced sandboxes are returned"
    (mt/with-premium-features #{:dependencies :sandboxes}
      (let [mp (mt/metadata-provider)
            products (lib.metadata/table mp (mt/id :products))]
        (mt/with-temp [:model/PermissionsGroup {group-id :id} {:name "Sandbox Group - unreftest"}
                       :model/Card {sandbox-card-id :id} {:name "Sandbox Card - unreftest"
                                                          :type :question
                                                          :dataset_query (lib/query mp products)}
                       :model/Sandbox {sandbox-id :id} {:group_id group-id
                                                        :table_id (mt/id :products)
                                                        :card_id sandbox-card-id}]
          (deps.test/synchronously-run-dependency-job!)
          (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/unreferenced?types=sandbox")]
            (is (=? {:data [{:id sandbox-id
                             :type "sandbox"
                             :data {:table {:name "PRODUCTS"}}}]}
                    response))))))))

(deftest ^:synchronized unreferenced-card-types-test
  (testing "GET /api/ee/dependencies/unreferenced - unreferenced models and metrics are filtered by card-types and pagination"
    (mt/with-premium-features #{:dependencies}
      (let [mp (mt/metadata-provider)
            products (lib.metadata/table mp (mt/id :products))]
        (mt/with-temp [:model/Card {unreffed-model-id :id} {:name "A - Unreferenced Model - cardtype"
                                                            :type :model
                                                            :dataset_query (lib/query mp products)}
                       :model/Card {unreffed-metric-id :id} {:name "B - Unreferenced Metric - cardtype"
                                                             :type :metric
                                                             :dataset_query (lib/query mp products)}]
          (deps.test/synchronously-run-dependency-job!)
          (testing "filtering by model only"
            (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/unreferenced?types=card&card-types=model&query=cardtype")]
              (is (=? {:data [{:id unreffed-model-id
                               :type "card"
                               :data {:name "A - Unreferenced Model - cardtype"
                                      :type "model"}}]}
                      response))))
          (testing "filtering by metric only"
            (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/unreferenced?types=card&card-types=metric&query=cardtype")]
              (is (=? {:data [{:id unreffed-metric-id
                               :type "card"
                               :data {:name "B - Unreferenced Metric - cardtype"
                                      :type "metric"}}]}
                      response))))
          (testing "filtering by model and metric as the default card types"
            (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/unreferenced?types=card&query=cardtype")]
              (is (=? {:data [{:id unreffed-model-id
                               :type "card"
                               :data {:name "A - Unreferenced Model - cardtype"
                                      :type "model"}}
                              {:id unreffed-metric-id
                               :type "card"
                               :data {:name "B - Unreferenced Metric - cardtype"
                                      :type "metric"}}]}
                      response)))))))))

(deftest ^:synchronized unreferenced-archived-card-test
  (testing "GET /api/ee/dependencies/graph/unreferenced with archived parameter"
    (mt/with-premium-features #{:dependencies}
      (let [mp (mt/metadata-provider)
            products (lib.metadata/table mp (mt/id :products))]
        (mt/with-temp [:model/Card {unreffed-card-id :id} {:name "Unreferenced Card - archivedtest"
                                                           :type :question
                                                           :dataset_query (lib/query mp products)}
                       :model/Card {archived-card-id :id} {:name "Archived Unreferenced Card - archivedtest"
                                                           :type :question
                                                           :archived true
                                                           :dataset_query (lib/query mp products)}]
          (deps.test/synchronously-run-dependency-job!)
          (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/unreferenced?types=card&card-types=question&query=archivedtest")
                card-ids (set (map :id (:data response)))]
            (is (contains? card-ids unreffed-card-id))
            (is (not (contains? card-ids archived-card-id)))))))))

(deftest ^:synchronized unreferenced-archived-dashboard-test
  (testing "GET /api/ee/dependencies/graph/unreferenced with archived parameter for dashboards"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/Dashboard {unreffed-dashboard-id :id} {:name "Unreferenced Dashboard - archivedtest"}
                     :model/Dashboard {archived-dashboard-id :id} {:name "Archived Unreferenced Dashboard - archivedtest"
                                                                   :archived true}]
        (deps.test/synchronously-run-dependency-job!)
        (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/unreferenced?types=dashboard&query=archivedtest")
              dashboard-ids (set (map :id (:data response)))]
          (is (contains? dashboard-ids unreffed-dashboard-id))
          (is (not (contains? dashboard-ids archived-dashboard-id))))))))

(deftest ^:synchronized unreferenced-archived-document-test
  (testing "GET /api/ee/dependencies/graph/unreferenced with archived parameter for documents"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/Document {unreffed-document-id :id} {:name "Unreferenced Document - archivedtest"}
                     :model/Document {archived-document-id :id} {:name "Archived Unreferenced Document - archivedtest"
                                                                 :archived true}]
        (deps.test/synchronously-run-dependency-job!)
        (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/unreferenced?types=document&query=archivedtest")
              document-ids (set (map :id (:data response)))]
          (is (contains? document-ids unreffed-document-id))
          (is (not (contains? document-ids archived-document-id))))))))

(deftest ^:synchronized unreferenced-archived-snippet-test
  (testing "GET /api/ee/dependencies/graph/unreferenced with archived parameter for snippets"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/NativeQuerySnippet {unreffed-snippet-id :id} {:name "Unreferenced Snippet - archivedtest"
                                                                          :content "WHERE ID > 10"}
                     :model/NativeQuerySnippet {archived-snippet-id :id} {:name "Archived Unreferenced Snippet - archivedtest"
                                                                          :content "WHERE ID > 20"
                                                                          :archived true}]
        (deps.test/synchronously-run-dependency-job!)
        (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/unreferenced?types=snippet&query=archivedtest")
              snippet-ids (set (map :id (:data response)))]
          (is (contains? snippet-ids unreffed-snippet-id))
          (is (not (contains? snippet-ids archived-snippet-id))))))))

(deftest ^:synchronized unreferenced-excludes-internal-content-test
  (testing "GET /api/ee/dependencies/graph/unreferenced excludes system-managed (internal-user) content"
    (mt/with-premium-features #{:dependencies}
      (let [mp (mt/metadata-provider)
            products (lib.metadata/table mp (mt/id :products))]
        (mt/with-temp [:model/Card {regular-card-id :id} {:name "Regular Card - intcontent"
                                                          :type :question
                                                          :dataset_query (lib/query mp products)}
                       :model/Card {internal-card-id :id} {:name "Internal Card - intcontent"
                                                           :type :question
                                                           :creator_id config/internal-mb-user-id
                                                           :dataset_query (lib/query mp products)}
                       :model/Dashboard {regular-dashboard-id :id} {:name "Regular Dashboard - intcontent"}
                       :model/Dashboard {internal-dashboard-id :id} {:name "Internal Dashboard - intcontent"
                                                                     :creator_id config/internal-mb-user-id}]
          (deps.test/synchronously-run-dependency-job!)
          (testing "internal-user cards are filtered out"
            (let [response (mt/user-http-request :crowberto :get 200
                                                 "ee/dependencies/graph/unreferenced?types=card&query=intcontent")
                  card-ids (set (map :id (:data response)))]
              (is (contains? card-ids regular-card-id))
              (is (not (contains? card-ids internal-card-id)))))
          (testing "internal-user dashboards are filtered out"
            (let [response (mt/user-http-request :crowberto :get 200
                                                 "ee/dependencies/graph/unreferenced?types=dashboard&query=intcontent")
                  dashboard-ids (set (map :id (:data response)))]
              (is (contains? dashboard-ids regular-dashboard-id))
              (is (not (contains? dashboard-ids internal-dashboard-id))))))))))

(deftest ^:synchronized breaking-entities-includes-internal-content-test
  (testing "GET /api/ee/dependencies/graph/breaking still surfaces internal-user (system-managed) content"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/User user {:email "[email protected]"}]
        (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus :model/AnalysisFinding :model/AnalysisFindingError]
          (let [[internal-model dependent-card]
                (lib-be/with-metadata-provider-cache
                  (let [internal-model (create-model-card! user "Internal Model - intbreaking")
                        dependent-card (create-dependent-card-on-model! user internal-model "Dependent - intbreaking")]
                    [internal-model dependent-card]))]
            (t2/update! :model/Card :id (:id internal-model) {:creator_id config/internal-mb-user-id})
            (lib-be/with-metadata-provider-cache
              (break-model-card! (t2/select-one :model/Card :id (:id internal-model))))
            (lib-be/with-metadata-provider-cache
              (deps.test/synchronously-run-dependency-job!)
              (run-analysis-for-card! (:id dependent-card)))
            (let [response (mt/user-http-request :crowberto :get 200
                                                 "ee/dependencies/graph/breaking?types=card&query=intbreaking")
                  card-ids (set (map :id (:data response)))]
              (is (contains? card-ids (:id internal-model))
                  "Internal-user model card should still appear in breaking list"))))))))

(deftest ^:synchronized unreferenced-archived-segment-test
  (testing "GET /api/ee/dependencies/graph/unreferenced with archived parameter for segments"
    (mt/with-premium-features #{:dependencies}
      (let [products-id (mt/id :products)
            price-field-id (mt/id :products :price)]
        (mt/with-temp [:model/Segment {unreffed-segment-id :id :as unreffed-segment} {:name "Unreferenced Segment - archivedtest"
                                                                                      :table_id products-id
                                                                                      :definition {:filter [:> [:field price-field-id nil] 50]}}
                       :model/Segment {archived-segment-id :id :as archived-segment} {:name "Archived Unreferenced Segment - archivedtest"
                                                                                      :table_id products-id
                                                                                      :definition {:filter [:> [:field price-field-id nil] 100]}
                                                                                      :archived true}]
          (events/publish-event! :event/segment-create {:object unreffed-segment :user-id (mt/user->id :crowberto)})
          (events/publish-event! :event/segment-create {:object archived-segment :user-id (mt/user->id :crowberto)})
          (deps.test/synchronously-run-dependency-job!)
          (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/unreferenced?types=segment&query=archivedtest")
                segment-ids (set (map :id (:data response)))]
            (is (contains? segment-ids unreffed-segment-id))
            (is (not (contains? segment-ids archived-segment-id)))))))))

(deftest ^:synchronized unreferenced-archived-table-test
  (testing "GET /api/ee/dependencies/graph/unreferenced includes inactive and hidden tables"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/Table {active-table-id :id} {:name "Active Unreferenced Table - archivedtest"
                                                         :db_id (mt/id)
                                                         :active true}
                     :model/Table {inactive-table-id :id} {:name "Inactive Unreferenced Table - archivedtest"
                                                           :db_id (mt/id)
                                                           :active false}
                     :model/Table {hidden-table-id :id} {:name "Hidden Unreferenced Table - archivedtest"
                                                         :db_id (mt/id)
                                                         :active true
                                                         :visibility_type "hidden"}]
        (deps.test/synchronously-run-dependency-job!)
        (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/unreferenced?types=table&query=archivedtest")
              table-ids (set (map :id (:data response)))]
          (is (contains? table-ids active-table-id))
          (testing "inactive tables are always included"
            (is (contains? table-ids inactive-table-id)))
          (testing "hidden tables are always included"
            (is (contains? table-ids hidden-table-id))))))))

(deftest ^:synchronized unreferenced-pagination-test
  (testing "GET /api/ee/dependencies/unreferenced - should paginate results"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/Table {table1-id :id} {:name "Table 1 - unreftest"}
                     :model/Table {table2-id :id} {:name "Table 2 - unreftest"}
                     :model/Table {table3-id :id} {:name "Table 3 - unreftest"}]
        (deps.test/synchronously-run-dependency-job!)
        (is (=? {:data   [{:id table1-id} {:id table2-id}]
                 :total  3
                 :offset 0
                 :limit  2}
                (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/unreferenced?types=table&query=unreftest&offset=0&limit=2")))
        (is (=? {:data   [{:id table3-id}]
                 :total  3
                 :offset 2
                 :limit  2}
                (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/unreferenced?types=table&query=unreftest&offset=2&limit=2")))))))

(deftest ^:synchronized unreferenced-sample-db-test
  (testing "GET /api/ee/dependencies/unreferenced - should not return tables from the sample database"
    (mt/with-premium-features #{:dependencies}
      (mt/with-empty-h2-app-db!
        (mt/with-temp [:model/Database {db-id :id} {:is_sample true}
                       :model/Table    _           {:db_id db-id :name "Sample DB table - unreftest"}]
          (is (=? {:data   []
                   :total  0}
                  (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/unreferenced?types=table&query=unreftest"))))))))

(deftest ^:synchronized unreferenced-audit-db-test
  (testing "GET /api/ee/dependencies/unreferenced - should not return tables from the audit database"
    (mt/with-premium-features #{:dependencies}
      (mt/with-empty-h2-app-db!
        (mbc/ensure-audit-db-installed!)
        (is (=? {:data   []
                 :total  0}
                (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/unreferenced?types=table&query=notification")))))))

(deftest ^:synchronized unreferenced-archived-measure-test
  (testing "GET /api/ee/dependencies/graph/unreferenced with archived parameter for measures"
    (mt/with-premium-features #{:dependencies}
      (let [mp (mt/metadata-provider)
            products-id (mt/id :products)
            products (lib.metadata/table mp products-id)
            price (lib.metadata/field mp (mt/id :products :price))
            measure-definition (-> (lib/query mp products)
                                   (lib/aggregate (lib/sum price)))]
        (mt/with-temp [:model/Measure {unreffed-measure-id :id :as unreffed-measure} {:name "Unreferenced Measure - archivedtest"
                                                                                      :table_id products-id
                                                                                      :definition measure-definition}
                       :model/Measure {archived-measure-id :id :as archived-measure} {:name "Archived Unreferenced Measure - archivedtest"
                                                                                      :table_id products-id
                                                                                      :definition measure-definition
                                                                                      :archived true}]
          (events/publish-event! :event/measure-create {:object unreffed-measure :user-id (mt/user->id :crowberto)})
          (events/publish-event! :event/measure-create {:object archived-measure :user-id (mt/user->id :crowberto)})
          (deps.test/synchronously-run-dependency-job!)
          (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/unreferenced?types=measure&query=archivedtest")
                measure-ids (set (map :id (:data response)))]
            (is (contains? measure-ids unreffed-measure-id))
            (is (not (contains? measure-ids archived-measure-id)))))))))

(deftest ^:synchronized unreferenced-personal-collection-card-test
  (testing "GET /api/ee/dependencies/graph/unreferenced with include-personal-collections parameter for cards"
    (mt/with-premium-features #{:dependencies}
      (binding [collection/*allow-deleting-personal-collections* true]
        (let [mp (mt/metadata-provider)
              products (lib.metadata/table mp (mt/id :products))]
          (mt/with-temp [:model/User {user-id :id} {}
                         :model/Collection {sub-personal-coll-id :id} {:name "Sub Personal Collection"
                                                                       :location (format "/%d/" (personal-collection-id user-id))}
                         :model/Card {card-in-personal :id} {:name "Card in Personal - personalcolltest"
                                                             :type :question
                                                             :collection_id (personal-collection-id user-id)
                                                             :dataset_query (lib/query mp products)}
                         :model/Card {card-in-sub-personal :id} {:name "Card in Sub Personal - personalcolltest"
                                                                 :type :question
                                                                 :collection_id sub-personal-coll-id
                                                                 :dataset_query (lib/query mp products)}
                         :model/Card {card-regular :id} {:name "Card Regular - personalcolltest"
                                                         :type :question
                                                         :dataset_query (lib/query mp products)}]
            (deps.test/synchronously-run-dependency-job!)
            (testing "include-personal-collections=false (default) excludes cards in personal collections"
              (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/unreferenced?types=card&card-types=question&query=personalcolltest")
                    card-ids (set (map :id (:data response)))]
                (is (not (contains? card-ids card-in-personal)))
                (is (not (contains? card-ids card-in-sub-personal)))
                (is (contains? card-ids card-regular))))
            (testing "include-personal-collections=true includes cards in personal collections"
              (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/unreferenced?types=card&card-types=question&query=personalcolltest&include-personal-collections=true")
                    card-ids (set (map :id (:data response)))]
                (is (contains? card-ids card-in-personal))
                (is (contains? card-ids card-in-sub-personal))
                (is (contains? card-ids card-regular))))))))))

(deftest ^:synchronized unreferenced-personal-collection-dashboard-test
  (testing "GET /api/ee/dependencies/graph/unreferenced with include-personal-collections parameter for dashboards"
    (mt/with-premium-features #{:dependencies}
      (binding [collection/*allow-deleting-personal-collections* true]
        (mt/with-temp [:model/User {user-id :id} {}
                       :model/Dashboard {dash-in-personal :id} {:name "Dashboard in Personal - personalcolltest"
                                                                :collection_id (personal-collection-id user-id)}
                       :model/Dashboard {dash-regular :id} {:name "Dashboard Regular - personalcolltest"}]
          (deps.test/synchronously-run-dependency-job!)
          (testing "include-personal-collections=false (default) excludes dashboards in personal collections"
            (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/unreferenced?types=dashboard&query=personalcolltest")
                  dashboard-ids (set (map :id (:data response)))]
              (is (not (contains? dashboard-ids dash-in-personal)))
              (is (contains? dashboard-ids dash-regular))))
          (testing "include-personal-collections=true includes dashboards in personal collections"
            (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/unreferenced?types=dashboard&query=personalcolltest&include-personal-collections=true")
                  dashboard-ids (set (map :id (:data response)))]
              (is (contains? dashboard-ids dash-in-personal))
              (is (contains? dashboard-ids dash-regular)))))))))

(deftest ^:synchronized unreferenced-sort-by-name-test
  (testing "GET /api/ee/dependencies/graph/unreferenced - sorting by name"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/Card               _ {:name "A Card sorttest"}
                     :model/Table              _ {:name "B Table sorttest"
                                                  :display_name "B Table sorttest"}
                     :model/Transform          _ {:name "C Transform sorttest"}
                     :model/NativeQuerySnippet _ {:name "D Snippet sorttest"}
                     :model/Dashboard          _ {:name "E Dashboard sorttest"}
                     :model/Document           _ {:name "F Document sorttest"}
                     :model/Segment            _ {:name "G Segment sorttest"}
                     :model/Measure            _ {:name "H Measure sorttest"}]
        (deps.test/synchronously-run-dependency-job!)
        (doseq [sort-direction [:asc :desc]]
          (let [response (mt/user-http-request :crowberto :get 200
                                               "ee/dependencies/graph/unreferenced"
                                               :query "sorttest"
                                               :sort-column :name
                                               :sort-direction sort-direction)
                names (mapv #(get-in % [:data :name]) (:data response))]
            (is (= (cond-> ["A Card sorttest"
                            "B Table sorttest"
                            "C Transform sorttest"
                            "D Snippet sorttest"
                            "E Dashboard sorttest"
                            "F Document sorttest"
                            "G Segment sorttest"
                            "H Measure sorttest"]
                     (= sort-direction :desc) reverse)
                   names))))))))

(deftest ^:synchronized unreferenced-sort-by-location-test
  (testing "GET /api/ee/dependencies/graph/unreferenced - sorting by location"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [;; locations
                     :model/Database   {db-id :id}          {:name "A Database"}
                     :model/Table      {table1-id :id}      {:name "B Table"
                                                             :display_name "B Table"
                                                             :db_id db-id}
                     :model/Table      {table2-id :id}      {:name "C Table"
                                                             :display_name "C Table"
                                                             :db_id db-id}
                     :model/Collection {collection1-id :id} {:name "D Collection"}
                     :model/Collection {collection2-id :id} {:name "E Collection"
                                                             :namespace :transforms}
                     :model/Collection {collection3-id :id} {:name "F Collection"
                                                             :namespace :snippets}
                     :model/Collection {collection4-id :id} {:name "G Collection"}
                     :model/Collection {collection5-id :id} {:name "H Collection"}
                     :model/Dashboard  {dashboard-id :id}   {:name "I Dashboard"
                                                             :collection_id collection1-id}
                     :model/Document   {document-id :id}    {:name "J Document"
                                                             :collection_id collection1-id}
                     ;; entities
                     :model/Card               _ {:name          "Card with Collection 1 sorttest"
                                                  :collection_id collection1-id}
                     :model/Card               _ {:name          "Card with Dashboard sorttest"
                                                  :collection_id collection1-id
                                                  :dashboard_id  dashboard-id}
                     :model/Card               _ {:name          "Card with Document sorttest"
                                                  :collection_id collection1-id
                                                  :document_id   document-id}
                     :model/Table              _ {:name         "Table with Database sorttest"
                                                  :display_name "Table sorttest"
                                                  :db_id        db-id}
                     :model/Transform          _ {:name          "Transform with Collection 2 sorttest"
                                                  :collection_id collection2-id}
                     :model/NativeQuerySnippet _ {:name          "Snippet with Collection 3 sorttest"
                                                  :collection_id collection3-id}
                     :model/Dashboard          _ {:name          "Dashboard with Collection 4 sorttest"
                                                  :collection_id collection4-id}
                     :model/Document           _ {:name          "Document with Collection 5 sorttest"
                                                  :collection_id collection5-id}
                     :model/Segment            _ {:name     "Segment with Table 1 sorttest"
                                                  :table_id table1-id}
                     :model/Measure            _ {:name     "Measure with Table 2 sorttest"
                                                  :table_id table2-id}]
        (deps.test/synchronously-run-dependency-job!)
        (doseq [sort-direction [:asc :desc]]
          (let [response (mt/user-http-request :crowberto :get 200
                                               "ee/dependencies/graph/unreferenced"
                                               :query "sorttest"
                                               :sort-column :location
                                               :sort-direction sort-direction)
                names (mapv #(get-in % [:data :name]) (:data response))]
            (is (= (cond-> ["Table with Database sorttest"
                            "Segment with Table 1 sorttest"
                            "Measure with Table 2 sorttest"
                            "Card with Collection 1 sorttest"
                            "Transform with Collection 2 sorttest"
                            "Snippet with Collection 3 sorttest"
                            "Dashboard with Collection 4 sorttest"
                            "Document with Collection 5 sorttest"
                            "Card with Dashboard sorttest"
                            "Card with Document sorttest"]
                     (= sort-direction :desc) reverse)
                   names))))))))

(deftest ^:synchronized unreferenced-sort-by-location-with-root-collection-test
  (testing "GET /api/ee/dependencies/graph/unreferenced - sorting by location with root collection"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/Collection {collection1-id :id} {:name "Collection 1"}
                     :model/Card               _ {:name "Our analytics sorttest"}
                     :model/Card               _ {:name "Collection 1 sorttest"
                                                  :collection_id collection1-id}
                     :model/NativeQuerySnippet _ {:name "SQL snippets sorttest"}
                     :model/Transform          _ {:name "Transforms sorttest"}]
        (deps.test/synchronously-run-dependency-job!)
        (doseq [sort-direction [:asc :desc]]
          (let [response (mt/user-http-request :crowberto :get 200
                                               "ee/dependencies/graph/unreferenced"
                                               :query "sorttest"
                                               :sort-column :location
                                               :sort-direction sort-direction)
                names (mapv #(get-in % [:data :name]) (:data response))]
            (is (= (cond-> ["Collection 1 sorttest"
                            "Our analytics sorttest"
                            "SQL snippets sorttest"
                            "Transforms sorttest"]
                     (= sort-direction :desc) reverse)
                   names))))))))

(deftest ^:synchronized breaking-entities-returns-source-of-errors-test
  (testing "GET /api/ee/dependencies/graph/breaking - returns entities that are SOURCE of downstream errors"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/User user {:email "[email protected]"}]
        (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus :model/AnalysisFinding :model/AnalysisFindingError]
          ;; Create cards in one metadata provider cache session
          (let [[model-card dependent-card]
                (lib-be/with-metadata-provider-cache
                  (let [model-card (create-model-card! user "Model Card - brokentest")
                        dependent-card (create-dependent-card-on-model! user model-card "Dependent Card - brokentest")]
                    [model-card dependent-card]))]
            (lib-be/with-metadata-provider-cache
              (break-model-card! model-card))
            ;; Run analysis in a fresh metadata provider cache session to detect the broken reference
            (lib-be/with-metadata-provider-cache
              (deps.test/synchronously-run-dependency-job!)
              (run-analysis-for-card! (:id dependent-card)))
            (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/breaking?types=card&query=brokentest")]
              (is (= [(:id model-card)] (mapv :id (:data response)))
                  "Model card should appear as a breaking entity"))))))))

(deftest ^:synchronized breaking-entities-types-filtering-test
  (testing "GET /api/ee/dependencies/graph/breaking - types parameter filters results"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/User user {:email "[email protected]"}]
        (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus :model/AnalysisFinding :model/AnalysisFindingError]
          ;; Create cards in one metadata provider cache session
          (let [[model-card-1 model-card-2 dependent-card-1 dependent-card-2]
                (lib-be/with-metadata-provider-cache
                  (let [model-card-1 (create-model-card! user "Model Card 1 - typesfiltertest")
                        model-card-2 (create-model-card! user "Model Card 2 - typesfiltertest")
                        dependent-card-1 (create-dependent-card-on-model! user model-card-1 "Dependent Card 1 - typesfiltertest")
                        dependent-card-2 (create-dependent-card-on-model! user model-card-2 "Dependent Card 2 - typesfiltertest")]
                    [model-card-1 model-card-2 dependent-card-1 dependent-card-2]))]
            ;; Break both models
            (lib-be/with-metadata-provider-cache
              (break-model-card! model-card-1)
              (break-model-card! model-card-2))
            ;; Run analysis in a fresh metadata provider cache session to detect broken references
            (lib-be/with-metadata-provider-cache
              (deps.test/synchronously-run-dependency-job!)
              (run-analysis-for-card! (:id dependent-card-1))
              (run-analysis-for-card! (:id dependent-card-2)))
            (testing "filtering by card returns only card sources"
              (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/breaking?types=card&query=typesfiltertest")
                    ids (set (map :id (:data response)))]
                (is (contains? ids (:id model-card-1)) "Model card 1 should be in results")
                (is (contains? ids (:id model-card-2)) "Model card 2 should be in results")))
            (testing "filtering by table returns empty (no table sources in this test)"
              (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/breaking?types=table&query=typesfiltertest")
                    ids (set (map :id (:data response)))]
                (is (empty? ids) "No tables should be in results")))))))))

(deftest ^:synchronized breaking-entities-archived-card-test
  (testing "GET /api/ee/dependencies/graph/breaking includes archived source cards that break a non-archived dependent"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/User user {:email "[email protected]"}]
        (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus :model/AnalysisFinding :model/AnalysisFindingError]
          ;; Create cards in one metadata provider cache session
          (let [[active-model archived-model dependent-card-1 dependent-card-2]
                (lib-be/with-metadata-provider-cache
                  (let [active-model (create-model-card! user "Active Model - archivedbrokentestcard")
                        archived-model (create-model-card! user "Archived Model - archivedbrokentestcard")
                        dependent-card-1 (create-dependent-card-on-model! user active-model "Dependent of Active - archivedbrokentestcard")
                        dependent-card-2 (create-dependent-card-on-model! user archived-model "Dependent of Archived - archivedbrokentestcard")]
                    [active-model archived-model dependent-card-1 dependent-card-2]))]
            ;; Archive the second model
            (card/update-card! {:card-before-update archived-model
                                :card-updates {:archived true}})
            ;; Break both models
            (lib-be/with-metadata-provider-cache
              (break-model-card! active-model)
              (break-model-card! (t2/select-one :model/Card :id (:id archived-model))))
            ;; Run analysis in a fresh metadata provider cache session to detect broken references
            (lib-be/with-metadata-provider-cache
              (deps.test/synchronously-run-dependency-job!)
              (run-analysis-for-card! (:id dependent-card-1))
              (run-analysis-for-card! (:id dependent-card-2)))
            (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/breaking?types=card&query=archivedbrokentestcard")
                  card-ids (set (map :id (:data response)))]
              (is (contains? card-ids (:id active-model)))
              ;; The archived model is itself a breaking source: its non-archived dependent
              ;; (dependent-card-2) has an error traced back to it, so it should be surfaced.
              (is (contains? card-ids (:id archived-model))))))))))

(deftest ^:synchronized breaking-entities-inactive-table-test
  (testing "GET /api/ee/dependencies/graph/breaking?types=table includes an inactive table that breaks a non-archived dependent"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/Database db    {:engine :h2, :name "inactive-table-breaking-test"}
                     :model/Table    table {:db_id (:id db), :name "RETIRED_TABLE", :active true}
                     :model/Field    _field {:table_id (:id table), :name "ID"
                                             :base_type :type/Integer, :database_type "INTEGER"}
                     :model/User     user  {:email "[email protected]"}]
        (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus
                                :model/AnalysisFinding :model/AnalysisFindingError]
          (let [query (lib-be/with-metadata-provider-cache
                        (let [mp (lib-be/application-database-metadata-provider (:id db))]
                          (lib/query mp (lib.metadata/table mp (:id table)))))]
            (mt/with-temp [:model/Card card {:database_id   (:id db)
                                             :dataset_query query
                                             :type          :question
                                             :name          "Dependent of retired table"
                                             :creator_id    (:id user)}
                           :model/Dependency _dep {:from_entity_type "card",  :from_entity_id (:id card)
                                                   :to_entity_type   "table", :to_entity_id   (:id table)}]
              (t2/update! :model/Table :id (:id table) {:active false})
              (lib-be/with-metadata-provider-cache
                (run-analysis-for-card! (:id card)))
              (testing "the dependent card's analysis is now broken, attributing the inactive table as the source"
                (is (false? (t2/select-one-fn :result :model/AnalysisFinding
                                              :entity_type "card" :entity_id (:id card))))
                (is (t2/exists? :model/AnalysisFindingError
                                :source_entity_type "table" :source_entity_id (:id table)
                                :analyzed_entity_type "card" :analyzed_entity_id (:id card))))
              (testing "the inactive table is surfaced as a breaking source"
                (let [response  (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/breaking?types=table")
                      table-ids (set (map :id (:data response)))]
                  (is (contains? table-ids (:id table))))))))))))

(deftest ^:synchronized breaking-entities-multiple-dependents-test
  (testing "GET /api/ee/dependencies/graph/breaking - model breaking multiple dependents appears once"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/User user {:email "[email protected]"}]
        (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus :model/AnalysisFinding :model/AnalysisFindingError]
          ;; Create cards in one metadata provider cache session
          (let [[model-card dependent-card-1 dependent-card-2]
                (lib-be/with-metadata-provider-cache
                  (let [model-card (create-model-card! user "Model Card - multipledependents")
                        dependent-card-1 (create-dependent-card-on-model! user model-card "Dependent 1 - multipledependents")
                        dependent-card-2 (create-dependent-card-on-model! user model-card "Dependent 2 - multipledependents")]
                    [model-card dependent-card-1 dependent-card-2]))]
            ;; Break the model
            (lib-be/with-metadata-provider-cache
              (break-model-card! model-card))
            ;; Run analysis in a fresh metadata provider cache session to detect broken references
            (lib-be/with-metadata-provider-cache
              (deps.test/synchronously-run-dependency-job!)
              (run-analysis-for-card! (:id dependent-card-1))
              (run-analysis-for-card! (:id dependent-card-2)))
            (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/breaking?types=card&query=multipledependents")
                  model-ids (filter #(= (:id %) (:id model-card)) (:data response))]
              (is (= 1 (count model-ids)) "Model should appear exactly once even with multiple broken dependents"))))))))

(deftest ^:synchronized breaking-entities-personal-collection-card-test
  (testing "GET /api/ee/dependencies/graph/breaking with include-personal-collections parameter"
    (mt/with-premium-features #{:dependencies}
      (binding [collection/*allow-deleting-personal-collections* true]
        (mt/with-temp [:model/User {user-id :id} {}
                       :model/User creator {:email "[email protected]"}]
          (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus :model/AnalysisFinding :model/AnalysisFindingError]
            ;; Create cards in one metadata provider cache session
            (let [[model-in-personal model-regular dependent-card-1 dependent-card-2]
                  (lib-be/with-metadata-provider-cache
                    (let [model-in-personal (create-model-card! creator "Model in Personal - personalcollbrokentest"
                                                                :collection-id (personal-collection-id user-id))
                          model-regular (create-model-card! creator "Model Regular - personalcollbrokentest")
                          dependent-card-1 (create-dependent-card-on-model! creator model-in-personal "Dependent of Personal - personalcollbrokentest")
                          dependent-card-2 (create-dependent-card-on-model! creator model-regular "Dependent of Regular - personalcollbrokentest")]
                      [model-in-personal model-regular dependent-card-1 dependent-card-2]))]
              ;; Break both models
              (lib-be/with-metadata-provider-cache
                (break-model-card! model-in-personal)
                (break-model-card! model-regular))
              ;; Run analysis in a fresh metadata provider cache session to detect broken references
              (lib-be/with-metadata-provider-cache
                (deps.test/synchronously-run-dependency-job!)
                (run-analysis-for-card! (:id dependent-card-1))
                (run-analysis-for-card! (:id dependent-card-2)))
              (testing "include-personal-collections=false (default) excludes source cards in personal collections"
                (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/breaking?types=card&query=personalcollbrokentest")
                      card-ids (set (map :id (:data response)))]
                  (is (not (contains? card-ids (:id model-in-personal))))
                  (is (contains? card-ids (:id model-regular)))))
              (testing "include-personal-collections=true includes source cards in personal collections"
                (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/breaking?types=card&query=personalcollbrokentest&include-personal-collections=true")
                      card-ids (set (map :id (:data response)))]
                  (is (contains? card-ids (:id model-in-personal)))
                  (is (contains? card-ids (:id model-regular))))))))))))

(deftest ^:synchronized breaking-entities-pagination-test
  (testing "GET /api/ee/dependencies/graph/breaking - should paginate results"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/User user {:email "[email protected]"}]
        (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus :model/AnalysisFinding :model/AnalysisFindingError]
          ;; Create cards in one metadata provider cache session
          (let [[model-card-1 model-card-2 dependent-card-1 dependent-card-2]
                (lib-be/with-metadata-provider-cache
                  (let [model-card-1 (create-model-card! user "A Model Card - paginationtest")
                        model-card-2 (create-model-card! user "B Model Card - paginationtest")
                        dependent-card-1 (create-dependent-card-on-model! user model-card-1 "Dependent Card 1 - paginationtest")
                        dependent-card-2 (create-dependent-card-on-model! user model-card-2 "Dependent Card 2 - paginationtest")]
                    [model-card-1 model-card-2 dependent-card-1 dependent-card-2]))]
            ;; Break both models
            (lib-be/with-metadata-provider-cache
              (break-model-card! model-card-1)
              (break-model-card! model-card-2))
            ;; Run analysis in a fresh metadata provider cache session to detect broken references
            (lib-be/with-metadata-provider-cache
              (deps.test/synchronously-run-dependency-job!)
              (run-analysis-for-card! (:id dependent-card-1))
              (run-analysis-for-card! (:id dependent-card-2)))
            (is (=? {:data   [{:id (:id model-card-1)}]
                     :total  2
                     :offset 0
                     :limit  1}
                    (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/breaking?types=card&query=paginationtest&offset=0&limit=1")))
            (is (=? {:data   [{:id (:id model-card-2)}]
                     :total  2
                     :offset 1
                     :limit  1}
                    (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/breaking?types=card&query=paginationtest&offset=1&limit=1")))))))))

(deftest ^:synchronized breaking-entities-sort-by-name-test
  (testing "GET /api/ee/dependencies/graph/breaking - sorting by name"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/User user {:email "[email protected]"}]
        (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus :model/AnalysisFinding :model/AnalysisFindingError]
          ;; Create cards in one metadata provider cache session
          (let [[model-card-a model-card-b dependent-card-a dependent-card-b]
                (lib-be/with-metadata-provider-cache
                  (let [model-card-a (create-model-card! user "A Card sortnametest")
                        model-card-b (create-model-card! user "B Card sortnametest")
                        dependent-card-a (create-dependent-card-on-model! user model-card-a "Dependent A - sortnametest")
                        dependent-card-b (create-dependent-card-on-model! user model-card-b "Dependent B - sortnametest")]
                    [model-card-a model-card-b dependent-card-a dependent-card-b]))]
            ;; Break both models
            (lib-be/with-metadata-provider-cache
              (break-model-card! model-card-a)
              (break-model-card! model-card-b))
            ;; Run analysis in a fresh metadata provider cache session to detect broken references
            (lib-be/with-metadata-provider-cache
              (deps.test/synchronously-run-dependency-job!)
              (run-analysis-for-card! (:id dependent-card-a))
              (run-analysis-for-card! (:id dependent-card-b)))
            (doseq [sort-direction [:asc :desc]]
              (let [response (mt/user-http-request :crowberto :get 200
                                                   "ee/dependencies/graph/breaking"
                                                   :types "card"
                                                   :query "sortnametest"
                                                   :sort-column :name
                                                   :sort-direction sort-direction)
                    names (mapv #(get-in % [:data :name]) (:data response))]
                (is (= (cond-> ["A Card sortnametest"
                                "B Card sortnametest"]
                         (= sort-direction :desc) reverse)
                       names))))))))))

(deftest ^:synchronized breaking-entities-sort-by-location-test
  (testing "GET /api/ee/dependencies/graph/breaking - sorting by location"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/User user {:email "[email protected]"}
                     :model/Collection {collection1-id :id} {:name "B Collection"}
                     :model/Collection {collection2-id :id} {:name "A Collection"}]
        (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus :model/AnalysisFinding :model/AnalysisFindingError]
          ;; Create cards in one metadata provider cache session
          (let [[model-in-coll1 model-in-coll2 dependent-card-1 dependent-card-2]
                (lib-be/with-metadata-provider-cache
                  (let [model-in-coll1 (create-model-card! user "Card with Collection 1 sortloctest" :collection-id collection1-id)
                        model-in-coll2 (create-model-card! user "Card with Collection 2 sortloctest" :collection-id collection2-id)
                        dependent-card-1 (create-dependent-card-on-model! user model-in-coll1 "Dependent of Coll1 - sortloctest")
                        dependent-card-2 (create-dependent-card-on-model! user model-in-coll2 "Dependent of Coll2 - sortloctest")]
                    [model-in-coll1 model-in-coll2 dependent-card-1 dependent-card-2]))]
            ;; Break both models
            (lib-be/with-metadata-provider-cache
              (break-model-card! model-in-coll1)
              (break-model-card! model-in-coll2))
            ;; Run analysis in a fresh metadata provider cache session to detect broken references
            (lib-be/with-metadata-provider-cache
              (deps.test/synchronously-run-dependency-job!)
              (run-analysis-for-card! (:id dependent-card-1))
              (run-analysis-for-card! (:id dependent-card-2)))
            (doseq [sort-direction [:asc :desc]]
              (let [response (mt/user-http-request :crowberto :get 200
                                                   "ee/dependencies/graph/breaking"
                                                   :types "card"
                                                   :query "sortloctest"
                                                   :sort-column :location
                                                   :sort-direction sort-direction)
                    names (mapv #(get-in % [:data :name]) (:data response))]
                (is (= (cond-> ["Card with Collection 2 sortloctest"
                                "Card with Collection 1 sortloctest"]
                         (= sort-direction :desc) reverse)
                       names))))))))))

(deftest ^:synchronized breaking-entities-sort-by-dependents-with-errors-count-test
  (testing "GET /api/ee/dependencies/graph/breaking - sorting by dependents with errors count"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/User user {:email "[email protected]"}]
        (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus :model/AnalysisFinding :model/AnalysisFindingError]
          ;; Create cards in one metadata provider cache session
          (let [[model-card-1 model-card-2 dependent-card-1a dependent-card-1b dependent-card-2a]
                (lib-be/with-metadata-provider-cache
                  (let [model-card-1 (create-model-card! user "Card 1 sortdepstest")
                        model-card-2 (create-model-card! user "Card 2 sortdepstest")
                        ;; Model 1 has 2 dependents, Model 2 has 1 dependent
                        dependent-card-1a (create-dependent-card-on-model! user model-card-1 "Dependent 1a - sortdepstest")
                        dependent-card-1b (create-dependent-card-on-model! user model-card-1 "Dependent 1b - sortdepstest")
                        dependent-card-2a (create-dependent-card-on-model! user model-card-2 "Dependent 2a - sortdepstest")]
                    [model-card-1 model-card-2 dependent-card-1a dependent-card-1b dependent-card-2a]))]
            ;; Break both models
            (lib-be/with-metadata-provider-cache
              (break-model-card! model-card-1)
              (break-model-card! model-card-2))
            ;; Run analysis in a fresh metadata provider cache session to detect broken references
            (lib-be/with-metadata-provider-cache
              (deps.test/synchronously-run-dependency-job!)
              (run-analysis-for-card! (:id dependent-card-1a))
              (run-analysis-for-card! (:id dependent-card-1b))
              (run-analysis-for-card! (:id dependent-card-2a)))
            (doseq [sort-direction [:asc :desc]]
              (let [response (mt/user-http-request :crowberto :get 200
                                                   "ee/dependencies/graph/breaking"
                                                   :types "card"
                                                   :query "sortdepstest"
                                                   :sort-column :dependents-with-errors
                                                   :sort-direction sort-direction)
                    names (mapv #(get-in % [:data :name]) (:data response))]
                (is (= (cond-> ["Card 2 sortdepstest"
                                "Card 1 sortdepstest"]
                         (= sort-direction :desc) reverse)
                       names))))))))))

(deftest ^:synchronized breaking-entities-sort-by-dependents-with-errors-test
  (testing "GET /api/ee/dependencies/graph/breaking - sorting by dependents with errors count"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/User user {:email "[email protected]"}]
        (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus :model/AnalysisFinding :model/AnalysisFindingError]
          ;; Create cards in one metadata provider cache session
          ;; Model 1 breaks 2 dependent cards (2 unique analyzed entities with errors)
          ;; Model 2 breaks 1 dependent card (1 unique analyzed entity with errors)
          (let [[model-card-1 model-card-2 dependent-card-1a dependent-card-1b dependent-card-2a]
                (lib-be/with-metadata-provider-cache
                  (let [model-card-1 (create-model-card! user "Card 1 sorterrorstest")
                        model-card-2 (create-model-card! user "Card 2 sorterrorstest")
                        dependent-card-1a (create-dependent-card-on-model! user model-card-1 "Dependent 1a - sorterrorstest")
                        dependent-card-1b (create-dependent-card-on-model! user model-card-1 "Dependent 1b - sorterrorstest")
                        dependent-card-2a (create-dependent-card-on-model! user model-card-2 "Dependent 2a - sorterrorstest")]
                    [model-card-1 model-card-2 dependent-card-1a dependent-card-1b dependent-card-2a]))]
            ;; Break both models
            (lib-be/with-metadata-provider-cache
              (break-model-card! model-card-1)
              (break-model-card! model-card-2))
            ;; Run analysis in a fresh metadata provider cache session to detect broken references
            (lib-be/with-metadata-provider-cache
              (deps.test/synchronously-run-dependency-job!)
              (run-analysis-for-card! (:id dependent-card-1a))
              (run-analysis-for-card! (:id dependent-card-1b))
              (run-analysis-for-card! (:id dependent-card-2a)))
            (doseq [sort-direction [:asc :desc]]
              (let [response (mt/user-http-request :crowberto :get 200
                                                   "ee/dependencies/graph/breaking"
                                                   :types "card"
                                                   :query "sorterrorstest"
                                                   :sort-column :dependents-with-errors
                                                   :sort-direction sort-direction)
                    names (mapv #(get-in % [:data :name]) (:data response))]
                ;; Card 2 has 1 broken dependent, Card 1 has 2 broken dependents
                ;; Ascending: fewer errors first, Descending: more errors first
                (is (= (cond-> ["Card 2 sorterrorstest"
                                "Card 1 sorterrorstest"]
                         (= sort-direction :desc) reverse)
                       names))))))))))

(defn- get-dependents
  "Helper to call the /graph/dependents endpoint."
  [base-card-id & opts]
  (apply mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/dependents"
         :id base-card-id :type "card" opts))

(defn- create-dependent!
  "Create a dependent card with the given name."
  [base-card user card-name & opts]
  (card/create-card! (apply assoc (wrap-card base-card) :name card-name opts) user))

(defmacro ^:private with-dependents-test!
  [[user-binding base-card-binding] & body]
  `(mt/with-premium-features #{:dependencies}
     (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus]
       (mt/with-temp [:model/User user# {:email "[email protected]"}]
         (let [~user-binding user#
               ~base-card-binding (card/create-card! (basic-card "Base") user#)]
           ~@body)))))

(deftest ^:synchronized dependents-query-filter-test
  (testing "GET /api/ee/dependencies/graph/dependents with query parameter"
    (with-dependents-test! [user {base-card-id :id :as base-card}]
      (create-dependent! base-card user "Alpha")
      (create-dependent! base-card user "Beta")
      (create-dependent! base-card user "Gamma")
      (deps.test/synchronously-run-dependency-job!)
      (testing "filters by name"
        (is (=? [{:data {:name "Alpha"}}]
                (get-dependents base-card-id :query "Alpha"))))
      (testing "query is case-insensitive"
        (is (=? [{:data {:name "Beta"}}]
                (get-dependents base-card-id :query "BETA"))))
      (testing "no query returns all dependents"
        (is (= 3 (count (get-dependents base-card-id))))))))

(deftest ^:synchronized dependents-query-filter-by-location-test
  (testing "GET /api/ee/dependencies/graph/dependents query filters by location (collection name)"
    (with-dependents-test! [user {base-card-id :id :as base-card}]
      (mt/with-temp [:model/Collection {coll-id :id} {:name "SpecialCollection"}]
        (create-dependent! base-card user "Card in root")
        (create-dependent! base-card user "Card in collection" :collection_id coll-id)
        (deps.test/synchronously-run-dependency-job!)
        (is (=? [{:data {:name "Card in collection"}}]
                (get-dependents base-card-id :query "SpecialCollection")))))))

(deftest ^:synchronized dependents-personal-collections-test
  (testing "GET /api/ee/dependencies/graph/dependents with include-personal-collections parameter"
    (binding [collection/*allow-deleting-personal-collections* true]
      (with-dependents-test! [{user-id :id :as user} {base-card-id :id :as base-card}]
        (mt/with-temp [:model/Collection {sub-coll-id :id} {:location (format "/%d/" (personal-collection-id user-id))}]
          (create-dependent! base-card user "In Personal" :collection_id (personal-collection-id user-id))
          (create-dependent! base-card user "In Sub" :collection_id sub-coll-id)
          (create-dependent! base-card user "Regular")
          (deps.test/synchronously-run-dependency-job!)
          (testing "default excludes personal collections"
            (is (=? [{:data {:name "Regular"}}]
                    (get-dependents base-card-id))))
          (testing "include-personal-collections=true includes them"
            (is (= 3 (count (get-dependents base-card-id :include-personal-collections true))))))))))

(deftest ^:synchronized dependents-sort-by-name-test
  (testing "GET /api/ee/dependencies/graph/dependents - sorting by name"
    (with-dependents-test! [user {base-card-id :id :as base-card}]
      (create-dependent! base-card user "C Card")
      (create-dependent! base-card user "A Card")
      (create-dependent! base-card user "B Card")
      (deps.test/synchronously-run-dependency-job!)
      (is (=? [{:data {:name "A Card"}} {:data {:name "B Card"}} {:data {:name "C Card"}}]
              (get-dependents base-card-id :sort-column :name :sort-direction :asc)))
      (is (=? [{:data {:name "C Card"}} {:data {:name "B Card"}} {:data {:name "A Card"}}]
              (get-dependents base-card-id :sort-column :name :sort-direction :desc))))))

(deftest ^:synchronized dependents-sort-by-location-test
  (testing "GET /api/ee/dependencies/graph/dependents - sorting by location"
    (with-dependents-test! [user {base-card-id :id :as base-card}]
      (mt/with-temp [:model/Collection {coll-a :id} {:name "A Collection"}
                     :model/Collection {coll-b :id} {:name "B Collection"}
                     :model/Collection {coll-c :id} {:name "C Collection"}]
        (create-dependent! base-card user "In C" :collection_id coll-c)
        (create-dependent! base-card user "In A" :collection_id coll-a)
        (create-dependent! base-card user "In B" :collection_id coll-b)
        (deps.test/synchronously-run-dependency-job!)
        (is (=? [{:data {:name "In A"}} {:data {:name "In B"}} {:data {:name "In C"}}]
                (get-dependents base-card-id :sort-column :location :sort-direction :asc)))
        (is (=? [{:data {:name "In C"}} {:data {:name "In B"}} {:data {:name "In A"}}]
                (get-dependents base-card-id :sort-column :location :sort-direction :desc)))))))

(deftest ^:synchronized dependents-sort-by-view-count-test
  (testing "GET /api/ee/dependencies/graph/dependents - sorting by view-count"
    (with-dependents-test! [user {base-card-id :id :as base-card}]
      (let [{low-id :id} (create-dependent! base-card user "Low")
            {mid-id :id} (create-dependent! base-card user "Mid")
            {high-id :id} (create-dependent! base-card user "High")]
        (deps.test/synchronously-run-dependency-job!)
        (t2/update! :model/Card :id low-id {:view_count 10})
        (t2/update! :model/Card :id mid-id {:view_count 50})
        (t2/update! :model/Card :id high-id {:view_count 100})
        (is (=? [{:data {:view_count 10}} {:data {:view_count 50}} {:data {:view_count 100}}]
                (get-dependents base-card-id :sort-column :view-count :sort-direction :asc)))
        (is (=? [{:data {:view_count 100}} {:data {:view_count 50}} {:data {:view_count 10}}]
                (get-dependents base-card-id :sort-column :view-count :sort-direction :desc)))))))

(deftest ^:synchronized dependents-sort-view-count-mixed-types-test
  (testing "GET /api/ee/dependencies/graph/dependents - view-count sorting with mixed entity types"
    (with-dependents-test! [user {base-card-id :id :as base-card}]
      (mt/with-model-cleanup [:model/DashboardCard]
        (mt/with-temp [:model/Dashboard {dashboard-id :id} {:name "Dashboard" :view_count 200}]
          (let [{low-id :id} (create-dependent! base-card user "Low")
                {high-id :id} (create-dependent! base-card user "High")]
            (t2/insert! :model/DashboardCard {:dashboard_id dashboard-id :card_id base-card-id
                                              :row 0 :col 0 :size_x 4 :size_y 4})
            (events/publish-event! :event/dashboard-update {:object (t2/select-one :model/Dashboard :id dashboard-id) :user-id (mt/user->id :crowberto)})
            (deps.test/synchronously-run-dependency-job!)
            (t2/update! :model/Card :id low-id {:view_count 10})
            (t2/update! :model/Card :id high-id {:view_count 100})
            (is (=? [{:data {:view_count 10}} {:data {:view_count 100}} {:data {:view_count 200}}]
                    (get-dependents base-card-id :sort-column :view-count :sort-direction :asc)))
            (is (=? [{:data {:view_count 200}} {:data {:view_count 100}} {:data {:view_count 10}}]
                    (get-dependents base-card-id :sort-column :view-count :sort-direction :desc)))))))))

(deftest ^:synchronized dependents-query-and-sort-combined-test
  (testing "GET /api/ee/dependencies/graph/dependents with query and sort together"
    (with-dependents-test! [user {base-card-id :id :as base-card}]
      (create-dependent! base-card user "C Match")
      (create-dependent! base-card user "A Match")
      (create-dependent! base-card user "B Match")
      (create-dependent! base-card user "Should not appear")
      (deps.test/synchronously-run-dependency-job!)
      (is (=? [{:data {:name "A Match"}} {:data {:name "B Match"}} {:data {:name "C Match"}}]
              (get-dependents base-card-id :query "Match" :sort-column :name :sort-direction :asc))))))

(deftest ^:synchronized node-errors-filtering-test
  (testing "node-errors filters by source visibility"
    (mt/with-current-user (mt/user->id :rasta)
      (mt/with-temp [:model/Collection {coll-id :id}     {}
                     :model/Card       {card-id :id}     {:collection_id coll-id}
                     :model/Card       {visible-src :id} {:collection_id coll-id}
                     :model/Card       {archived-src :id} {:collection_id coll-id :archived true}]
        ;; Create errors: one with visible source, one with archived source, one with nil source
        (t2/insert! :model/AnalysisFindingError
                    [{:analyzed_entity_type "card"
                      :analyzed_entity_id   card-id
                      :source_entity_type   "card"
                      :source_entity_id     visible-src
                      :error_type           "missing-column"
                      :error_detail         "col1"}
                     {:analyzed_entity_type "card"
                      :analyzed_entity_id   card-id
                      :source_entity_type   "card"
                      :source_entity_id     archived-src
                      :error_type           "missing-column"
                      :error_detail         "col2"}
                     {:analyzed_entity_type "card"
                      :analyzed_entity_id   card-id
                      :source_entity_type   nil
                      :source_entity_id     nil
                      :error_type           "syntax-error"}])
        (let [result      (#'deps.api/node-errors {:card [card-id]})
              card-errors (get result [:card card-id])]
          (testing "includes errors with visible source"
            (is (contains? card-errors {:type :missing-column :detail "col1"})))
          (testing "excludes errors with archived source"
            (is (not (contains? card-errors {:type :missing-column :detail "col2"}))))
          (testing "includes errors with nil source"
            (is (contains? card-errors {:type :syntax-error}))))))))

(deftest ^:synchronized node-downstream-errors-filtering-test
  (testing "node-downstream-errors filters by analyzed entity visibility"
    (mt/with-current-user (mt/user->id :rasta)
      (mt/with-temp [:model/Collection {coll-id :id}       {}
                     :model/Card       {source-card :id}   {:collection_id coll-id}
                     :model/Card       {visible-card :id}  {:collection_id coll-id}
                     :model/Card       {archived-card :id} {:collection_id coll-id :archived true}]
        ;; Create errors: one with visible analyzed entity, one with archived analyzed entity
        (t2/insert! :model/AnalysisFindingError
                    [{:analyzed_entity_type "card"
                      :analyzed_entity_id   visible-card
                      :source_entity_type   "card"
                      :source_entity_id     source-card
                      :error_type           "missing-column"}
                     {:analyzed_entity_type "card"
                      :analyzed_entity_id   archived-card
                      :source_entity_type   "card"
                      :source_entity_id     source-card
                      :error_type           "missing-column"}])
        (let [result      (#'deps.api/node-downstream-errors {:card [source-card]})
              card-errors (get result [:card source-card])]
          (testing "includes errors with visible analyzed entity"
            (is (= 1 (count card-errors))))
          (testing "the included error is the visible one"
            (is (= visible-card (:analyzed_entity_id (first card-errors))))))))))

(deftest ^:synchronized broken-endpoint-error-visibility-filtering-test
  (testing "GET /api/ee/dependencies/graph/breaking - pagination and sorting work with error visibility filtering"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/User user {:email "[email protected]"}]
        (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus :model/AnalysisFinding :model/AnalysisFindingError]
          ;; Create cards in one metadata provider cache session
          (let [[model-card-a model-card-b visible-dep-a visible-dep-b archived-dep-a archived-dep-b]
                (lib-be/with-metadata-provider-cache
                  (let [model-card-a (create-model-card! user "A Model - errvistest")
                        model-card-b (create-model-card! user "B Model - errvistest")
                        ;; Create visible dependents
                        visible-dep-a (create-dependent-card-on-model! user model-card-a "Visible Dep A - errvistest")
                        visible-dep-b (create-dependent-card-on-model! user model-card-b "Visible Dep B - errvistest")
                        ;; Create archived dependents
                        archived-dep-a (create-dependent-card-on-model! user model-card-a "Archived Dep A - errvistest")
                        archived-dep-b (create-dependent-card-on-model! user model-card-b "Archived Dep B - errvistest")]
                    [model-card-a model-card-b visible-dep-a visible-dep-b archived-dep-a archived-dep-b]))]
            ;; Archive the archived dependents
            (t2/update! :model/Card :id (:id archived-dep-a) {:archived true})
            (t2/update! :model/Card :id (:id archived-dep-b) {:archived true})
            ;; Break both models
            (lib-be/with-metadata-provider-cache
              (break-model-card! model-card-a)
              (break-model-card! model-card-b))
            ;; Run analysis to detect broken references
            (lib-be/with-metadata-provider-cache
              (deps.test/synchronously-run-dependency-job!)
              (run-analysis-for-card! (:id visible-dep-a))
              (run-analysis-for-card! (:id visible-dep-b))
              (run-analysis-for-card! (:id archived-dep-a))
              (run-analysis-for-card! (:id archived-dep-b)))
            (testing "pagination works correctly with error filtering"
              ;; Both model cards should appear in results with only visible errors
              (let [page-1 (mt/user-http-request :crowberto :get 200
                                                 "ee/dependencies/graph/breaking"
                                                 :types "card"
                                                 :query "errvistest"
                                                 :offset 0
                                                 :limit 1
                                                 :sort-column "name"
                                                 :sort-direction "asc")
                    page-2 (mt/user-http-request :crowberto :get 200
                                                 "ee/dependencies/graph/breaking"
                                                 :types "card"
                                                 :query "errvistest"
                                                 :offset 1
                                                 :limit 1
                                                 :sort-column "name"
                                                 :sort-direction "asc")]
                (testing "total count reflects all breaking entities"
                  (is (= 2 (:total page-1)))
                  (is (= 2 (:total page-2))))
                (testing "pagination returns different entities"
                  (is (= (:id model-card-a) (-> page-1 :data first :id)))
                  (is (= (:id model-card-b) (-> page-2 :data first :id))))))
            (testing "dependents_errors contains only errors for visible entities"
              (let [response (mt/user-http-request :crowberto :get 200
                                                   "ee/dependencies/graph/breaking"
                                                   :types "card"
                                                   :query "errvistest")
                    model-a-result (first (filter #(= (:id %) (:id model-card-a)) (:data response)))
                    model-b-result (first (filter #(= (:id %) (:id model-card-b)) (:data response)))
                    model-a-error-entities (set (map :analyzed_entity_id (:dependents_errors model-a-result)))
                    model-b-error-entities (set (map :analyzed_entity_id (:dependents_errors model-b-result)))]
                (testing "errors for visible dependents are included"
                  (is (contains? model-a-error-entities (:id visible-dep-a)))
                  (is (contains? model-b-error-entities (:id visible-dep-b))))
                (testing "errors for archived dependents are excluded"
                  (is (not (contains? model-a-error-entities (:id archived-dep-a))))
                  (is (not (contains? model-b-error-entities (:id archived-dep-b)))))))
            (testing "sorting by dependents-errors works with filtering"
              ;; Add extra errors to model-b so it has more visible errors
              (t2/insert! :model/AnalysisFindingError
                          {:analyzed_entity_type "card"
                           :analyzed_entity_id   (:id visible-dep-b)
                           :source_entity_type   "card"
                           :source_entity_id     (:id model-card-b)
                           :error_type           "missing-column"
                           :error_detail         "extra_col"})
              (let [asc-response (mt/user-http-request :crowberto :get 200
                                                       "ee/dependencies/graph/breaking"
                                                       :types "card"
                                                       :query "errvistest"
                                                       :sort-column "dependents-errors"
                                                       :sort-direction "asc")
                    desc-response (mt/user-http-request :crowberto :get 200
                                                        "ee/dependencies/graph/breaking"
                                                        :types "card"
                                                        :query "errvistest"
                                                        :sort-column "dependents-errors"
                                                        :sort-direction "desc")]
                (testing "ascending order puts fewer errors first"
                  (is (= (:id model-card-a) (-> asc-response :data first :id))))
                (testing "descending order puts more errors first"
                  (is (= (:id model-card-b) (-> desc-response :data first :id))))))))))))

(deftest ^:synchronized broken-endpoint-sort-by-visible-errors-only-test
  (testing "GET /api/ee/dependencies/graph/breaking - sorting counts only visible errors, not archived"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/User user {:email "[email protected]"}]
        (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus :model/AnalysisFinding :model/AnalysisFindingError]
          ;; Setup: Model A has fewer VISIBLE errors but more TOTAL errors (due to archived dependents)
          ;;        Model B has more VISIBLE errors but fewer TOTAL errors
          ;; If sorting counts all errors: A (3 total) > B (2 total) -> B first in asc
          ;; If sorting counts only visible: A (1 visible) < B (2 visible) -> A first in asc
          (let [[model-card-a model-card-b visible-dep-a visible-dep-b archived-dep-a-1 archived-dep-a-2]
                (lib-be/with-metadata-provider-cache
                  (let [model-card-a (create-model-card! user "A Model - sortviserr")
                        model-card-b (create-model-card! user "B Model - sortviserr")
                        visible-dep-a (create-dependent-card-on-model! user model-card-a "Visible Dep A - sortviserr")
                        visible-dep-b (create-dependent-card-on-model! user model-card-b "Visible Dep B - sortviserr")
                        archived-dep-a-1 (create-dependent-card-on-model! user model-card-a "Archived Dep A1 - sortviserr")
                        archived-dep-a-2 (create-dependent-card-on-model! user model-card-a "Archived Dep A2 - sortviserr")]
                    [model-card-a model-card-b visible-dep-a visible-dep-b archived-dep-a-1 archived-dep-a-2]))]
            ;; Archive model-a's extra dependents
            (t2/update! :model/Card :id (:id archived-dep-a-1) {:archived true})
            (t2/update! :model/Card :id (:id archived-dep-a-2) {:archived true})
            ;; Insert errors directly to ensure we control exactly what's in the DB
            ;; Model A: 1 visible error, 2 archived errors = 3 total
            ;; Model B: 2 visible errors = 2 total
            (t2/insert! :model/AnalysisFindingError
                        [{:analyzed_entity_type "card"
                          :analyzed_entity_id   (:id visible-dep-a)
                          :source_entity_type   "card"
                          :source_entity_id     (:id model-card-a)
                          :error_type           "missing-column"
                          :error_detail         "col1"}
                         {:analyzed_entity_type "card"
                          :analyzed_entity_id   (:id archived-dep-a-1)
                          :source_entity_type   "card"
                          :source_entity_id     (:id model-card-a)
                          :error_type           "missing-column"
                          :error_detail         "col2"}
                         {:analyzed_entity_type "card"
                          :analyzed_entity_id   (:id archived-dep-a-2)
                          :source_entity_type   "card"
                          :source_entity_id     (:id model-card-a)
                          :error_type           "missing-column"
                          :error_detail         "col3"}
                         {:analyzed_entity_type "card"
                          :analyzed_entity_id   (:id visible-dep-b)
                          :source_entity_type   "card"
                          :source_entity_id     (:id model-card-b)
                          :error_type           "missing-column"
                          :error_detail         "col4"}
                         {:analyzed_entity_type "card"
                          :analyzed_entity_id   (:id visible-dep-b)
                          :source_entity_type   "card"
                          :source_entity_id     (:id model-card-b)
                          :error_type           "missing-column"
                          :error_detail         "col5"}])
            (let [asc-response (mt/user-http-request :crowberto :get 200
                                                     "ee/dependencies/graph/breaking"
                                                     :types "card"
                                                     :query "sortviserr"
                                                     :sort-column "dependents-errors"
                                                     :sort-direction "asc")]
              (testing "ascending order should put A first (1 visible error < 2 visible errors)"
                ;; BUG: Without fix, this fails because sort counts total errors (A=3, B=2)
                ;; so B comes first. With fix, sort counts visible errors (A=1, B=2) so A comes first.
                (is (= (:id model-card-a) (-> asc-response :data first :id)))))))))))

(deftest ^:synchronized unreferenced-pagination-with-archived-items-test
  (testing "GET /api/ee/dependencies/graph/unreferenced - pagination works correctly with archived items"
    (mt/with-premium-features #{:dependencies}
      (mt/with-model-cleanup [:model/Dependency :model/DependencyStatus]
        (mt/with-temp [:model/Card _              {:name "A Card - unreftest" :archived true}
                       :model/Card {card2-id :id} {:name "B Card - unreftest"}
                       :model/Card {card3-id :id} {:name "C Card - unreftest"}]
          (deps.test/synchronously-run-dependency-job!)
          (let [response (mt/user-http-request :crowberto :get 200
                                               "ee/dependencies/graph/unreferenced"
                                               :types "card"
                                               :query "unreftest"
                                               :offset 0
                                               :limit 2
                                               :sort-column "name"
                                               :sort-direction "asc")]
            (is (=? {:data   [{:id card2-id} {:id card3-id}]
                     :total  2
                     :offset 0
                     :limit  2}
                    response))))))))

(deftest ^:synchronized unreferenced-pagination-with-archived-dependents-test
  (testing "GET /api/ee/dependencies/graph/unreferenced - should return items if all dependents are archived"
    (mt/with-premium-features #{:dependencies}
      (mt/with-model-cleanup [:model/Dependency :model/DependencyStatus]
        (mt/with-temp [:model/Card {card1-id :id, :as card1} {:name "A Card - unreftest"}
                       :model/Card card2                     {:name "B Card - unreftest"}
                       :model/Card {card3-id :id}            {:name "C Card - unreftest"
                                                              :dataset_query (wrap-card-query card1)
                                                              :archived true}
                       :model/Card {card4-id :id}            {:name "D Card - unreftest"
                                                              :dataset_query (wrap-card-query card2)}
                       :model/Card {card5-id :id}            {:name "E Card - unreftest"
                                                              :dataset_query (wrap-card-query card2)
                                                              :archived true}]
          (doseq [id [card1-id (:id card2) card3-id card4-id card5-id]]
            (events/publish-event! :event/card-create {:object (t2/select-one :model/Card :id id) :user-id (mt/user->id :crowberto)}))
          (deps.test/synchronously-run-dependency-job!)
          (let [response (mt/user-http-request :crowberto :get 200
                                               "ee/dependencies/graph/unreferenced"
                                               :types "card"
                                               :query "unreftest"
                                               :sort-column "name"
                                               :sort-direction "asc")]
            (is (=? {:data  [{:id card1-id}, {:id card4-id}]
                     :total 2}
                    response))))))))

;;; ------------------------------------------------ Table API Tests -------------------------------------------------
;;; Tests for dependency-related filtering on the /api/table endpoint

(deftest unused-only-filter-test
  (mt/with-premium-features #{:dependencies}
    (testing "GET /api/table?unused-only=true"
      (testing "filters tables that have no non-transform dependents"
        (mt/with-temp [:model/Database {db-id :id} {}
                       :model/Table {table-1-id :id} {:db_id db-id, :name "table_1", :active true}
                       :model/Table {table-2-id :id} {:db_id db-id, :name "table_2", :active true}]
          (testing "both tables returned without filter"
            (is (= #{table-1-id table-2-id}
                   (->> (mt/user-http-request :crowberto :get 200 "table")
                        (filter #(= (:db_id %) db-id))
                        (map :id)
                        set))))
          (testing "both tables returned with unused_only=false"
            (is (= #{table-1-id table-2-id}
                   (->> (mt/user-http-request :crowberto :get 200 "table" :unused-only false)
                        (filter #(= (:db_id %) db-id))
                        (map :id)
                        set))))
          (mt/with-temp [:model/Card card {:database_id   db-id
                                           :table_id      table-1-id
                                           :dataset_query {:database db-id
                                                           :type     :query
                                                           :query    {:source-table table-1-id}}}]
            (events/publish-event! :event/card-create {:object card :user-id (:creator_id card)})
            (deps.test/synchronously-run-dependency-job!)
            (testing "after creating card that depends on table-1, only table-2 is unused"
              (is (= #{table-2-id}
                     (->> (mt/user-http-request :crowberto :get 200 "table" :unused-only true)
                          (filter #(= (:db_id %) db-id))
                          (map :id)
                          set))))))))))

;;; --------------------------------------------- /graph/broken tests ---------------------------------------------
;;; Tests for the /graph/broken endpoint that returns broken dependents for a specific source entity.

(deftest ^:synchronized broken-dependents-source-filtering-test
  (testing "GET /api/ee/dependencies/graph/broken - returns broken dependents filtered by source"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/User user {:email "[email protected]"}]
        (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus :model/AnalysisFinding :model/AnalysisFindingError]
          ;; Setup: two models, each with one dependent
          (let [[model-card-1 model-card-2 dependent-card-1 dependent-card-2]
                (lib-be/with-metadata-provider-cache
                  (let [model-card-1 (create-model-card! user "Model Card 1 - sourcefiltertest")
                        model-card-2 (create-model-card! user "Model Card 2 - sourcefiltertest")
                        dependent-card-1 (create-dependent-card-on-model! user model-card-1
                                                                          "Dependent 1 - sourcefiltertest")
                        dependent-card-2 (create-dependent-card-on-model! user model-card-2
                                                                          "Dependent 2 - sourcefiltertest")]
                    [model-card-1 model-card-2 dependent-card-1 dependent-card-2]))]
            (lib-be/with-metadata-provider-cache
              (break-model-card! model-card-1)
              (break-model-card! model-card-2))
            (lib-be/with-metadata-provider-cache
              (deps.test/synchronously-run-dependency-job!)
              (run-analysis-for-card! (:id dependent-card-1))
              (run-analysis-for-card! (:id dependent-card-2)))
            (testing "returns only broken dependents for the specified source (not other sources)"
              (let [response (mt/user-http-request :crowberto :get 200
                                                   (str "ee/dependencies/graph/broken?id=" (:id model-card-1)
                                                        "&type=card"))]
                (is (= [(:id dependent-card-1)] (mapv :id response))
                    "Should return only dependent-card-1, not dependent-card-2 with errors from model-2")))))))))

(deftest ^:synchronized broken-count-and-sorting-test
  (testing "GET /api/ee/dependencies/graph/broken - count matches and sorting works"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/User user {:email "[email protected]"}]
        (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus :model/AnalysisFinding :model/AnalysisFindingError]
          ;; Setup: one model with two dependents (named for sorting)
          (let [[model-card dependent-card-a dependent-card-b]
                (lib-be/with-metadata-provider-cache
                  (let [model-card (create-model-card! user "Model Card - countsorttest")
                        dependent-card-a (create-dependent-card-on-model! user model-card
                                                                          "A Dependent - countsorttest")
                        dependent-card-b (create-dependent-card-on-model! user model-card
                                                                          "B Dependent - countsorttest")]
                    [model-card dependent-card-a dependent-card-b]))]
            (lib-be/with-metadata-provider-cache
              (break-model-card! model-card))
            (lib-be/with-metadata-provider-cache
              (deps.test/synchronously-run-dependency-job!)
              (run-analysis-for-card! (:id dependent-card-a))
              (run-analysis-for-card! (:id dependent-card-b)))
            (testing "count matches dependents-with-errors from /graph/breaking"
              (let [breaking-response (mt/user-http-request
                                       :crowberto :get 200
                                       "ee/dependencies/graph/breaking?types=card&query=countsorttest")
                    model-entry (first (filter #(= (:id %) (:id model-card)) (:data breaking-response)))
                    dependents-with-errors-count (count (:dependents_errors model-entry))
                    ;; Get actual broken dependents from new /graph/broken endpoint
                    broken-response (mt/user-http-request :crowberto :get 200
                                                          (str "ee/dependencies/graph/broken?id=" (:id model-card)
                                                               "&type=card"))]
                (is (= dependents-with-errors-count (count broken-response))
                    "Count from /graph/broken should match dependents_errors count from /graph/breaking")))
            (testing "sort by name ascending"
              (let [response (mt/user-http-request :crowberto :get 200
                                                   (str "ee/dependencies/graph/broken?id=" (:id model-card)
                                                        "&type=card&sort-column=name&sort-direction=asc"))
                    names (mapv #(get-in % [:data :name]) response)]
                (is (= ["A Dependent - countsorttest" "B Dependent - countsorttest"] names))))
            (testing "sort by name descending"
              (let [response (mt/user-http-request :crowberto :get 200
                                                   (str "ee/dependencies/graph/broken?id=" (:id model-card)
                                                        "&type=card&sort-column=name&sort-direction=desc"))
                    names (mapv #(get-in % [:data :name]) response)]
                (is (= ["B Dependent - countsorttest" "A Dependent - countsorttest"] names))))))))))

(deftest broken-requires-id-and-type-test
  (testing "GET /api/ee/dependencies/graph/broken - requires id and type parameters"
    (mt/with-premium-features #{:dependencies}
      (testing "missing both id and type returns 400"
        (mt/user-http-request :crowberto :get 400 "ee/dependencies/graph/broken"))
      (testing "missing type returns 400"
        (mt/user-http-request :crowberto :get 400 "ee/dependencies/graph/broken?id=1"))
      (testing "missing id returns 400"
        (mt/user-http-request :crowberto :get 400 "ee/dependencies/graph/broken?type=card")))))

(deftest ^:synchronized broken-requires-read-permission-test
  (testing "GET /api/ee/dependencies/graph/broken - requires read permission on source entity"
    (mt/with-premium-features #{:dependencies}
      (mt/with-non-admin-groups-no-root-collection-perms
        (mt/with-temp [:model/User user {:email "[email protected]"}
                       :model/Collection {coll-id :id} {:name "Private Collection"}]
          (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus :model/AnalysisFinding :model/AnalysisFindingError]
            (let [[model-card dependent-card]
                  (lib-be/with-metadata-provider-cache
                    (let [model-card (create-model-card! user "Model Card - permtest" :collection-id coll-id)
                          dependent-card (create-dependent-card-on-model! user model-card "Dependent Card - permtest"
                                                                          :collection-id coll-id)]
                      [model-card dependent-card]))]
              (lib-be/with-metadata-provider-cache
                (break-model-card! model-card))
              (lib-be/with-metadata-provider-cache
                (deps.test/synchronously-run-dependency-job!)
                (run-analysis-for-card! (:id dependent-card)))
              ;; Admin can access
              (is (sequential? (mt/user-http-request :crowberto :get 200
                                                     (str "ee/dependencies/graph/broken?id=" (:id model-card)
                                                          "&type=card"))))
              ;; Regular user without collection access gets 403
              (mt/user-http-request :rasta :get 403
                                    (str "ee/dependencies/graph/broken?id=" (:id model-card) "&type=card")))))))))

(deftest ^:synchronized broken-no-transitive-breakage-test
  (testing "GET /api/ee/dependencies/graph/broken - does not report transitive breakage"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/User user {:email "[email protected]"}]
        (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus :model/AnalysisFinding :model/AnalysisFindingError]
          ;; Create chain: model-1 -> model-2 -> card
          ;; When model-1 breaks:
          ;;   - model-2 gets error with source_entity_id=model-1
          ;;   - card gets error with source_entity_id=model-2 (NOT model-1)
          (let [[model-card-1 model-card-2 dependent-card]
                (lib-be/with-metadata-provider-cache
                  (let [model-card-1 (create-model-card! user "Model 1 - transitivetest")
                        ;; Create model-2 as a model that depends on model-1
                        model-card-2-question (create-dependent-card-on-model! user model-card-1
                                                                               "Model 2 - transitivetest")
                        model-card-2 (card/update-card! {:card-before-update model-card-2-question
                                                         :card-updates {:type :model}})
                        ;; Create card that depends on model-2
                        dependent-card (create-dependent-card-on-model! user model-card-2 "Card - transitivetest")]
                    [model-card-1 model-card-2 dependent-card]))]
            ;; Break model-1
            (lib-be/with-metadata-provider-cache
              (break-model-card! model-card-1))
            ;; Run analysis for both model-2 and dependent-card
            (lib-be/with-metadata-provider-cache
              (deps.test/synchronously-run-dependency-job!)
              (run-analysis-for-card! (:id model-card-2))
              (run-analysis-for-card! (:id dependent-card)))
            ;; Query /graph/broken for model-1 - should only return model-2, not dependent-card
            ;; because dependent-card's error source is model-2, not model-1
            (let [response (mt/user-http-request :crowberto :get 200
                                                 (str "ee/dependencies/graph/broken?id=" (:id model-card-1)
                                                      "&type=card"))]
              (is (= [(:id model-card-2)] (mapv :id response))
                  "Should return only model-2 (direct dependent), not card (transitive)"))))))))

(deftest ^:synchronized broken-filter-by-dependent-types-test
  (testing "GET /api/ee/dependencies/graph/broken - filters by dependent-types"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/User user {:email "[email protected]"}]
        (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus :model/AnalysisFinding :model/AnalysisFindingError]
          (let [[model-card dependent-card]
                (lib-be/with-metadata-provider-cache
                  (let [model-card (create-model-card! user "Model Card - deptypestest")
                        dependent-card (create-dependent-card-on-model! user model-card "Dependent Card - deptypestest")]
                    [model-card dependent-card]))]
            (lib-be/with-metadata-provider-cache
              (break-model-card! model-card))
            (lib-be/with-metadata-provider-cache
              (deps.test/synchronously-run-dependency-job!)
              (run-analysis-for-card! (:id dependent-card)))
            (testing "filtering by card type returns the dependent card"
              (let [response (mt/user-http-request :crowberto :get 200
                                                   (str "ee/dependencies/graph/broken?id=" (:id model-card)
                                                        "&type=card&dependent-types=card&dependent-card-types=question"))]
                (is (= [(:id dependent-card)] (mapv :id response)))))
            (testing "filtering by dashboard returns empty (no dashboards in this test)"
              (let [response (mt/user-http-request :crowberto :get 200
                                                   (str "ee/dependencies/graph/broken?id=" (:id model-card)
                                                        "&type=card&dependent-types=dashboard"))]
                (is (empty? response))))))))))

(deftest ^:synchronized broken-personal-collections-test
  (testing "GET /api/ee/dependencies/graph/broken with include-personal-collections parameter"
    (mt/with-premium-features #{:dependencies}
      (binding [collection/*allow-deleting-personal-collections* true]
        (mt/with-temp [:model/User {user-id :id} {}
                       :model/User creator {:email "[email protected]"}]
          (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus :model/AnalysisFinding :model/AnalysisFindingError]
            ;; one model, two dependents: one in personal collection, one in regular collection
            (let [[model-card dependent-in-personal dependent-regular]
                  (lib-be/with-metadata-provider-cache
                    (let [model-card (create-model-card! creator "Model - personalcollbrokentest2")
                          dependent-in-personal (create-dependent-card-on-model! creator model-card
                                                                                 "Dependent in Personal - personalcollbrokentest2"
                                                                                 :collection-id (personal-collection-id user-id))
                          dependent-regular (create-dependent-card-on-model! creator model-card
                                                                             "Dependent Regular - personalcollbrokentest2")]
                      [model-card dependent-in-personal dependent-regular]))]
              (lib-be/with-metadata-provider-cache
                (break-model-card! model-card))
              (lib-be/with-metadata-provider-cache
                (deps.test/synchronously-run-dependency-job!)
                (run-analysis-for-card! (:id dependent-in-personal))
                (run-analysis-for-card! (:id dependent-regular)))
              (testing "include-personal-collections=false (default) excludes broken dependents in personal collections"
                (let [response (mt/user-http-request :crowberto :get 200
                                                     (str "ee/dependencies/graph/broken?id=" (:id model-card) "&type=card"))
                      card-ids (set (map :id response))]
                  (is (not (contains? card-ids (:id dependent-in-personal))))
                  (is (contains? card-ids (:id dependent-regular)))))
              (testing "include-personal-collections=true includes broken dependents in personal collections"
                (let [response (mt/user-http-request :crowberto :get 200
                                                     (str "ee/dependencies/graph/broken?id=" (:id model-card)
                                                          "&type=card&include-personal-collections=true"))
                      card-ids (set (map :id response))]
                  (is (contains? card-ids (:id dependent-in-personal)))
                  (is (contains? card-ids (:id dependent-regular))))))))))))

(deftest ^:synchronized unreferenced-table-owner-test
  (testing "GET /api/ee/dependencies/unreferenced - table owner is returned"
    (mt/with-premium-features #{:dependencies}
      (mt/with-model-cleanup [:model/Dependency :model/DependencyStatus]
        (mt/with-temp [:model/Table {table1-id :id} {:name          "User Owned Table - ownertest"
                                                     :owner_user_id (mt/user->id :crowberto)}
                       :model/Table {table2-id :id} {:name        "Email Owned Table - ownertest"
                                                     :owner_email "[email protected]"}]
          (deps.test/synchronously-run-dependency-job!)
          (let [response (mt/user-http-request :crowberto :get 200
                                               "ee/dependencies/graph/unreferenced"
                                               :types "table" :query "ownertest"
                                               :sort-column "name" :sort-direction "asc")]
            (is (=? {:data [{:id   table2-id
                             :type "table"
                             :data {:name  "Email Owned Table - ownertest"
                                    :owner {:email "[email protected]"}}}
                            {:id   table1-id
                             :type "table"
                             :data {:name  "User Owned Table - ownertest"
                                    :owner {:id    (mt/user->id :crowberto)
                                            :email "[email protected]"}}}]}
                    response))))))))

(deftest ^:synchronized unreferenced-transform-owner-test
  (testing "GET /api/ee/dependencies/unreferenced - transform owner is returned"
    (mt/with-premium-features #{:dependencies}
      (let [mp       (mt/metadata-provider)
            products (lib.metadata/table mp (mt/id :products))]
        (mt/with-model-cleanup [:model/Dependency :model/DependencyStatus]
          (mt/with-temp [:model/Transform {transform1-id :id} {:name          "User Owned Transform - ownertest"
                                                               :owner_user_id (mt/user->id :crowberto)
                                                               :source        {:type  :query
                                                                               :query (lib/query mp products)}
                                                               :target        {:type "table" :schema "PUBLIC"
                                                                               :name   "user_owned_transform_table"}}
                         :model/Transform {transform2-id :id} {:name        "Email Owned Transform - ownertest"
                                                               :owner_email "[email protected]"
                                                               :source      {:type  :query
                                                                             :query (lib/query mp products)}
                                                               :target      {:type "table" :schema "PUBLIC"
                                                                             :name   "email_owned_transform_table"}}]
            (deps.test/synchronously-run-dependency-job!)
            (let [response (mt/user-http-request :crowberto :get 200
                                                 "ee/dependencies/graph/unreferenced"
                                                 :types "transform" :query "ownertest"
                                                 :sort-column "name" :sort-direction "asc")]
              (is (=? {:data [{:id   transform2-id
                               :type "transform"
                               :data {:name  "Email Owned Transform - ownertest"
                                      :owner {:email "[email protected]"}}}
                              {:id   transform1-id
                               :type "transform"
                               :data {:name  "User Owned Transform - ownertest"
                                      :owner {:id    (mt/user->id :crowberto)
                                              :email "[email protected]"}}}]}
                      response)))))))))

(deftest counts-access-test
  (testing "Dependency counts require authentication and the dependencies feature"
    (mt/with-premium-features #{:dependencies}
      (is (= "Unauthenticated" (mt/client :get 401 "ee/dependencies/counts"))))
    (mt/with-premium-features #{}
      (is (some? (mt/user-http-request :crowberto :get 402 "ee/dependencies/counts"))))))

(def ^:private monitor-list-params
  "The params the Monitor's Broken and Unreferenced tables send by default."
  {:breaking     {:types                        ["table" "card" "transform"]
                  :card-types                   ["question" "model"]
                  :include-personal-collections true}
   :unreferenced {:types                        ["table" "card" "segment" "measure" "snippet"]
                  :card-types                   ["question" "model" "metric"]
                  :include-personal-collections true}})

(defn- list-total
  "The `total` of the `query-type` list endpoint for `list-params`, plus any extra `params`."
  [user query-type list-params & params]
  (:total (apply mt/user-http-request user :get 200 (str "ee/dependencies/graph/" (name query-type))
                 (concat (mapcat identity list-params) params))))

(defn- default-dependency-list-total
  [user query-type & params]
  (apply list-total user query-type (monitor-list-params query-type) params))

(defn- counts
  "`/counts` for `list-params-by-type`, sending each list's params prefixed with its query type."
  [user list-params-by-type]
  (apply mt/user-http-request user :get 200 "ee/dependencies/counts"
         (for [[query-type list-params] list-params-by-type
               [k v] list-params
               x [(keyword (str (name query-type) "-" (name k))) v]]
           x)))

(defn- monitor-counts
  [user]
  (counts user monitor-list-params))

(deftest ^:synchronized counts-unreferenced-test
  (mt/with-premium-features #{:dependencies :transforms-basic :hosting}
    (let [baseline (default-dependency-list-total :crowberto :unreferenced)]
      (mt/with-temp [:model/User {user-id :id} {}
                     :model/Collection {personal-child-id :id}
                     {:location (format "/%d/" (personal-collection-id user-id))}
                     :model/Card {dependent-id :id} {}
                     :model/Card {referenced-id :id} {}
                     :model/Dependency _ {:from_entity_type :card :from_entity_id dependent-id
                                          :to_entity_type :card :to_entity_id referenced-id}
                     :model/Table _ {}
                     :model/Transform _ {}
                     :model/NativeQuerySnippet _ {}
                     :model/Dashboard _ {}
                     :model/Document _ {}
                     :model/Segment _ {}
                     :model/Measure _ {}
                     :model/Card _ {:archived true}
                     :model/Card _ {:collection_id (personal-collection-id user-id)}
                     :model/Dashboard _ {:collection_id personal-child-id}]
        (testing "Counts include the UI's default entity types and personal items, but not archived items"
          (is (= (+ baseline 6)
                 (:unreferenced (monitor-counts :crowberto)))))))))

(deftest ^:synchronized counts-params-test
  (mt/with-premium-features #{:dependencies :transforms-basic :hosting}
    (let [cases [[{:types ["card"] :card-types ["question"]} 1]
                 [{:types ["table"]} 1]
                 [{:types ["card"] :include-personal-collections true} 3]
                 [{:types ["card"] :include-personal-collections false} 2]]
          baseline-breaking (list-total :crowberto :breaking (monitor-list-params :breaking))
          baselines (mapv #(list-total :crowberto :unreferenced (first %)) cases)
          baseline-defaults {:breaking     (list-total :crowberto :breaking {})
                             :unreferenced (list-total :crowberto :unreferenced {})}]
      (mt/with-temp [:model/User {user-id :id} {}
                     :model/Card _ {:type :question}
                     :model/Card _ {:type :model}
                     :model/Table _ {}
                     :model/Card _ {:type :question :collection_id (personal-collection-id user-id)}]
        (testing "Each list is counted with its own prefixed params"
          (doseq [[[unreferenced-params increment] baseline] (map vector cases baselines)]
            (testing (pr-str unreferenced-params)
              (is (= {:breaking baseline-breaking :unreferenced (+ baseline increment)}
                     (counts :crowberto {:breaking     (monitor-list-params :breaking)
                                         :unreferenced unreferenced-params}))))))
        (testing "Omitted params use the list endpoints' defaults: all unreferenced types, no personal items"
          (is (= {:breaking     (:breaking baseline-defaults)
                  :unreferenced (+ (:unreferenced baseline-defaults) 3)}
                 (mt/user-http-request :crowberto :get 200 "ee/dependencies/counts"))))))))

(deftest ^:synchronized counts-breaking-sources-test
  (mt/with-premium-features #{:dependencies}
    (let [baseline (default-dependency-list-total :crowberto :breaking)]
      (mt/with-temp [:model/Card {source-id :id} {:archived true}
                     :model/Table {table-id :id} {}
                     :model/Card {dependent-a-id :id} {}
                     :model/Card {dependent-b-id :id} {}
                     :model/Card {archived-dependent-id :id} {:archived true}
                     :model/Card {archived-only-source-id :id} {}
                     :model/User {user-id :id} {}
                     :model/Card {personal-source-id :id} {:collection_id (personal-collection-id user-id)}
                     :model/AnalysisFindingError _ {:analyzed_entity_type :card
                                                    :analyzed_entity_id dependent-a-id
                                                    :source_entity_type :card :source_entity_id source-id
                                                    :error_type :missing-column :error_detail "column-a"}
                     :model/AnalysisFindingError _ {:analyzed_entity_type :card
                                                    :analyzed_entity_id dependent-a-id
                                                    :source_entity_type :card :source_entity_id source-id
                                                    :error_type :missing-column :error_detail "column-b"}
                     :model/AnalysisFindingError _ {:analyzed_entity_type :card
                                                    :analyzed_entity_id dependent-b-id
                                                    :source_entity_type :card :source_entity_id source-id
                                                    :error_type :missing-column}
                     :model/AnalysisFindingError _ {:analyzed_entity_type :card
                                                    :analyzed_entity_id dependent-a-id
                                                    :source_entity_type :table :source_entity_id table-id
                                                    :error_type :missing-column}
                     :model/AnalysisFindingError _ {:analyzed_entity_type :card
                                                    :analyzed_entity_id archived-dependent-id
                                                    :source_entity_type :card :source_entity_id archived-only-source-id
                                                    :error_type :missing-column}
                     :model/AnalysisFindingError _ {:analyzed_entity_type :card
                                                    :analyzed_entity_id dependent-a-id
                                                    :source_entity_type :card :source_entity_id personal-source-id
                                                    :error_type :missing-column}]
        (testing "Counts sources, including personal and archived sources still causing errors"
          (is (= (+ baseline 3)
                 (:breaking (monitor-counts :crowberto)))))
        (testing "The count agrees with the default table total, including when the table is paginated"
          (is (= (+ baseline 3)
                 (default-dependency-list-total :crowberto :breaking :limit 1))))))))

(deftest ^:synchronized counts-unreferenced-default-types-test
  (mt/with-premium-features #{:dependencies :transforms-basic :hosting}
    (let [baseline (default-dependency-list-total :crowberto :unreferenced)]
      (doseq [[model attrs increment] [[:model/Card {:type :question} 1]
                                       [:model/Card {:type :model} 1]
                                       [:model/Card {:type :metric} 1]
                                       [:model/Table {} 1]
                                       [:model/Segment {} 1]
                                       [:model/Measure {} 1]
                                       [:model/NativeQuerySnippet {} 1]
                                       [:model/Transform {} 0]
                                       [:model/Dashboard {} 0]
                                       [:model/Document {} 0]]]
        (testing (str model " " attrs)
          (mt/with-temp [model _ attrs]
            (is (= (+ baseline increment)
                   (default-dependency-list-total :crowberto :unreferenced :limit 1)))
            (is (= (+ baseline increment)
                   (:unreferenced (monitor-counts :crowberto))))))))))

(deftest ^:synchronized counts-breaking-default-types-test
  (mt/with-premium-features #{:dependencies :transforms-basic :hosting}
    (let [baseline (default-dependency-list-total :crowberto :breaking)]
      (doseq [[model attrs entity-type increment] [[:model/Card {:type :question} :card 1]
                                                   [:model/Card {:type :model} :card 1]
                                                   [:model/Card {:type :metric} :card 0]
                                                   [:model/Table {} :table 1]
                                                   [:model/Transform {} :transform 1]
                                                   [:model/Dashboard {} :dashboard 0]
                                                   [:model/Document {} :document 0]]]
        (testing (str model " " attrs)
          (mt/with-temp [model {source-id :id} attrs
                         :model/Card {dependent-id :id} {}
                         :model/AnalysisFindingError _ {:analyzed_entity_type :card
                                                        :analyzed_entity_id dependent-id
                                                        :source_entity_type entity-type
                                                        :source_entity_id source-id
                                                        :error_type :missing-column}]
            (is (= (+ baseline increment)
                   (default-dependency-list-total :crowberto :breaking :limit 1)))
            (is (= (+ baseline increment)
                   (:breaking (monitor-counts :crowberto))))))))))

(deftest ^:synchronized counts-visibility-test
  (mt/with-premium-features #{:dependencies}
    (mt/with-non-admin-groups-no-root-collection-perms
      (let [baseline-unreferenced (default-dependency-list-total :rasta :unreferenced)
            baseline-breaking (default-dependency-list-total :rasta :breaking)]
        (mt/with-temp [:model/Collection visible-collection {}
                       :model/Collection hidden-collection {}
                       :model/Card {visible-source-id :id} {:collection_id (:id visible-collection)}
                       :model/Card {visible-dependent-id :id} {:collection_id (:id visible-collection)}
                       :model/Card {hidden-source-id :id} {:collection_id (:id hidden-collection)}
                       :model/AnalysisFindingError _ {:analyzed_entity_type :card
                                                      :analyzed_entity_id visible-dependent-id
                                                      :source_entity_type :card :source_entity_id visible-source-id
                                                      :error_type :missing-column}
                       :model/AnalysisFindingError _ {:analyzed_entity_type :card
                                                      :analyzed_entity_id visible-dependent-id
                                                      :source_entity_type :card :source_entity_id hidden-source-id
                                                      :error_type :missing-column}]
          (perms/grant-collection-read-permissions! (perms/all-users-group) visible-collection)
          (testing "Non-admin counts are restricted to readable sources and items"
            (is (= {:breaking (inc baseline-breaking) :unreferenced (+ baseline-unreferenced 2)}
                   (monitor-counts :rasta))))
          (perms/revoke-collection-permissions! (perms/all-users-group) visible-collection)
          (perms/grant-collection-read-permissions! (perms/all-users-group) hidden-collection)
          (testing "A readable source is not breaking if its only broken dependent is unreadable"
            (is (= {:breaking baseline-breaking :unreferenced (inc baseline-unreferenced)}
                   (monitor-counts :rasta)))))))))

(deftest data-analyst-can-access-dependency-graph-test
  (mt/with-premium-features #{:advanced-permissions :data-studio :dependencies :transforms-basic :hosting}
    (testing "Data analysts can access dependency diagnostics endpoints"
      (let [data-analyst-group-id (:id (perms-group/data-analyst))]
        (mt/with-temp [:model/User {analyst-id :id} {:first_name "Data"
                                                     :last_name "Analyst"
                                                     :email "[email protected]"
                                                     :is_data_analyst true}
                       :model/PermissionsGroupMembership _ {:user_id analyst-id
                                                            :group_id data-analyst-group-id}
                       ;; the sample database: All Users may query it, so analyst-wide transform visibility applies
                       :model/Transform {transform-id :id} {:source_database_id (mt/id)
                                                            :name "Analyst Grace Transform - gracetest"}]
          (letfn [(unreferenced-transform-ids []
                    (->> (mt/user-http-request analyst-id :get 200
                                               "ee/dependencies/graph/unreferenced?types=transform&query=gracetest")
                         :data
                         (map :id)
                         set))]
            (testing "graph/unreferenced"
              (is (contains? (unreferenced-transform-ids) transform-id)))
            (testing "graph/breaking"
              (is (map? (mt/user-http-request analyst-id :get 200
                                              "ee/dependencies/graph/breaking"))))
            (testing "graph with transform"
              (is (map? (mt/user-http-request analyst-id :get 200
                                              (str "ee/dependencies/graph?type=transform&id=" transform-id)))))
            (testing "analyst-wide visibility pauses while advanced-permissions is unavailable"
              (mt/with-premium-features #{:data-studio :dependencies :transforms-basic :hosting}
                (is (not (contains? (unreferenced-transform-ids) transform-id)))))))))))

(defn- delete-venue-query []
  (lib/native-query (mt/metadata-provider) "DELETE FROM venues WHERE id = {{id}}"))

(deftest graph-root-data-action-permissions-test
  (testing "the graph shows a data action at the data-actions root only to users who can read that root"
    (mt/with-premium-features #{:dependencies}
      (mt/with-non-admin-groups-no-root-collection-for-namespace-perms :data-actions
        (mt/with-temp [:model/Action {action-id :id} {:type :query :name "Root data action permtest"}
                       :model/QueryAction _ {:action_id     action-id
                                             :database_id   (mt/id)
                                             :dataset_query (delete-venue-query)}]
          (mt/with-model-cleanup [:model/Dependency :model/DependencyStatus]
            (deps.test/synchronously-run-dependency-job!)
            (let [dependent-ids    (fn []
                                     (->> (mt/user-http-request :rasta :get 200 "ee/dependencies/graph/dependents"
                                                                :id (mt/id :venues)
                                                                :type "table"
                                                                :dependent-types "action")
                                          (into #{} (map :id))))
                  unreferenced-ids (fn []
                                     (->> (mt/user-http-request :rasta :get 200 "ee/dependencies/graph/unreferenced"
                                                                :types "action"
                                                                :query "permtest")
                                          :data
                                          (into #{} (map :id))))]
              (testing "a user who can read the default root but not the data-actions root"
                (is (not (contains? (dependent-ids) action-id)))
                (is (not (contains? (unreferenced-ids) action-id))))
              (testing "a user who can read the data-actions root"
                (perms/grant-collection-read-permissions! (perms/all-users-group)
                                                          (assoc collection/root-collection :namespace "data-actions"))
                (is (contains? (dependent-ids) action-id))
                (is (contains? (unreferenced-ids) action-id))))))))))

(deftest ^:synchronized unreferenced-root-data-action-location-test
  (testing "GET /api/ee/dependencies/graph/unreferenced locates a data action at the data-actions root in that root"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/Action {action-id :id} {:type :query :name "Root data action locationtest"}
                     :model/QueryAction _ {:action_id     action-id
                                           :database_id   (mt/id)
                                           :dataset_query (delete-venue-query)}]
        (mt/with-model-cleanup [:model/Dependency :model/DependencyStatus]
          (deps.test/synchronously-run-dependency-job!)
          (let [unreferenced (fn [query]
                               (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/unreferenced"
                                                     :types "action"
                                                     :query query))
                matches?     (fn [query]
                               (contains? (into #{} (map :id) (:data (unreferenced query))) action-id))]
            (testing "the response names the data-actions root"
              (is (=? {:data [{:id   action-id
                               :data {:collection {:name "Data actions" :namespace "data-actions"}}}]}
                      (unreferenced "locationtest"))))
            (testing "a search for the data-actions root name finds the action"
              (is (matches? "Data actions"))
              (is (not (matches? "Our analytics"))))))))))

(deftest backfill-status-requires-superuser-test
  (testing "GET /api/ee/dependencies/backfill-status scans every entity, so only superusers can call it"
    (mt/with-premium-features #{:dependencies}
      (is (= "You don't have permissions to do that."
             (mt/user-http-request :rasta :get 403 "ee/dependencies/backfill-status")))
      (is (=? {:complete boolean?}
              (mt/user-http-request :crowberto :get 200 "ee/dependencies/backfill-status"))))))

(deftest ^:synchronized backfill-status-failed-test
  (testing "GET /api/ee/dependencies/backfill-status lists an entity the job gave up on, which `complete` doesn't count"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/Card {card-id :id} (basic-card "Broken" :venues)]
        (mt/with-model-cleanup [:model/Dependency :model/DependencyStatus]
          (mt/with-dynamic-fn-redefs [deps.calculation/calculate-deps (fn [& _] (throw (ex-info "boom" {})))]
            (deps.test/synchronously-run-dependency-job!))
          (let [{:keys [complete failed]} (mt/user-http-request :crowberto :get 200 "ee/dependencies/backfill-status")]
            (is (true? complete))
            (is (some #{{:type "card" :id card-id}} failed)))
          (testing "a write gives the entity fresh attempts, so it is no longer failed"
            (dependencies.db/mark-dependency-statuses-stale! {:card #{card-id}})
            (deps.test/synchronously-run-dependency-job!)
            (is (not (some #{{:type "card" :id card-id}}
                           (:failed (mt/user-http-request :crowberto :get 200 "ee/dependencies/backfill-status")))))))))))

(defn- data-app-card
  "A question on venues in the data app resource collection with `collection-id`."
  [collection-id]
  (assoc (basic-card "Bird sightings" :venues) :collection_id collection-id))

(deftest ^:synchronized graph-data-app-test
  (testing "GET /api/ee/dependencies/graph shows what a data app depends on, and counts the app as a card's dependent"
    (mt/with-premium-features #{:dependencies :data-apps}
      (data-apps.tu/with-published-tables! [(mt/id :venues)]
        (mt/with-temp [:model/DataApp {app-id :id collection-id :resource_collection_id}
                       {:name "birds" :display_name "Birds" :description "Sightings" :bundle_path "birds.js"}
                       :model/Card {card-id :id} (data-app-card collection-id)]
          (mt/with-model-cleanup [:model/Dependency :model/DependencyStatus]
            (deps.test/synchronously-run-dependency-job!)
            (let [{:keys [nodes edges]} (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph"
                                                              :id app-id
                                                              :type "data-app")
                  node (fn [node-type node-id]
                         (m/find-first #(= [node-type node-id] ((juxt :type :id) %)) nodes))]
              (is (=? {:data {:name "birds" :display_name "Birds" :description "Sightings"}}
                      (node "data-app" app-id)))
              (is (=? {:dependents_count {:data-app 1}}
                      (node "card" card-id)))
              (is (some? (node "table" (mt/id :venues))))
              (is (contains? (into #{}
                                   (map (juxt :from_entity_type :from_entity_id :to_entity_type :to_entity_id))
                                   edges)
                             ["data-app" app-id "card" card-id])))))))))

(deftest ^:synchronized graph-data-app-dependents-test
  (testing "GET /api/ee/dependencies/graph/dependents lists the data apps a user can read"
    (data-apps.tu/with-published-tables! [(mt/id :venues)]
      (mt/with-temp [:model/DataApp {app-id :id collection-id :resource_collection_id}
                     {:name "birds" :display_name "Birds" :bundle_path "birds.js" :enabled false}
                     :model/Card {card-id :id} (data-app-card collection-id)]
        (mt/with-model-cleanup [:model/Dependency :model/DependencyStatus]
          (deps.test/synchronously-run-dependency-job!)
          (perms/grant-collection-read-permissions! (perms/all-users-group) collection-id)
          (let [dependent-ids (fn [user]
                                (->> (mt/user-http-request user :get 200 "ee/dependencies/graph/dependents"
                                                           :id card-id
                                                           :type "card"
                                                           :dependent-types "data-app")
                                     (into #{} (map :id))))]
            (mt/with-premium-features #{:dependencies :data-apps}
              (testing "an admin sees every app, disabled ones too"
                (is (= #{app-id} (dependent-ids :crowberto))))
              (testing "a user sees the enabled apps whose collection they can read"
                (is (= #{} (dependent-ids :rasta)))
                (t2/update! :model/DataApp :id app-id {:enabled true})
                (is (= #{app-id} (dependent-ids :rasta)))))
            (mt/with-premium-features #{:dependencies}
              (testing "without the data apps feature, the dependents list has no data apps, even for an admin"
                (is (= #{} (dependent-ids :crowberto)))))))))))

(deftest graph-data-app-names-only-for-non-admins-test
  (testing "GET /api/ee/dependencies/graph gives a non-admin only a data app's names, as the data-app API does"
    (mt/with-premium-features #{:dependencies :data-apps}
      (mt/with-temp [:model/DataApp {app-id :id collection-id :resource_collection_id}
                     {:name "birds" :display_name "Birds" :description "Sightings" :bundle_path "birds.js"}
                     :model/PermissionsGroup {group-id :id} {}
                     :model/PermissionsGroupMembership _ {:user_id (mt/user->id :rasta) :group_id group-id}]
        (perms/grant-collection-read-permissions! group-id collection-id)
        (let [app-data (fn [user]
                         (->> (mt/user-http-request user :get 200 "ee/dependencies/graph" :id app-id :type "data-app")
                              :nodes
                              (m/find-first #(= ["data-app" app-id] ((juxt :type :id) %)))
                              :data))]
          (is (= {:name "birds" :display_name "Birds"}
                 (app-data :rasta)))
          (testing "an admin also gets the description and creation time"
            (is (=? {:description "Sightings" :created_at some?}
                    (app-data :crowberto)))))))))

(deftest graph-data-app-without-data-apps-feature-test
  (testing "GET /api/ee/dependencies/graph refuses a data app start node without the data apps feature"
    (mt/with-premium-features #{:dependencies}
      (mt/with-temp [:model/DataApp {app-id :id collection-id :resource_collection_id}
                     {:name "birds" :display_name "Birds" :bundle_path "birds.js"}
                     :model/PermissionsGroup {group-id :id} {}
                     :model/PermissionsGroupMembership _ {:user_id (mt/user->id :rasta) :group_id group-id}]
        (perms/grant-collection-read-permissions! group-id collection-id)
        (doseq [[description user] [["to an admin" :crowberto]
                                    ["to a user in a group that can read the app's collection" :rasta]]]
          (testing description
            (is (= "You don't have permissions to do that."
                   (mt/user-http-request user :get 403 "ee/dependencies/graph" :id app-id :type "data-app")))))))))

(deftest ^:synchronized unreferenced-data-app-test
  (testing "GET /api/ee/dependencies/graph/unreferenced lists data apps, finds them by their display name, and sorts them
           by location"
    (mt/with-premium-features #{:dependencies :data-apps}
      (mt/with-temp [:model/DataApp {app-id :id} {:name "birds" :display_name "Bird sightings unreftest" :bundle_path "birds.js"}]
        (mt/with-model-cleanup [:model/Dependency :model/DependencyStatus]
          (deps.test/synchronously-run-dependency-job!)
          (let [unreferenced (fn [& params]
                               (->> (apply mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/unreferenced"
                                           :query "unreftest"
                                           params)
                                    :data
                                    (into #{} (map (juxt :type :id (comp :display_name :data))))))]
            (is (= #{["data-app" app-id "Bird sightings unreftest"]}
                   (unreferenced :types "data-app" :sort-column "location")))
            (testing "without a types filter"
              (is (= #{["data-app" app-id "Bird sightings unreftest"]}
                     (unreferenced))))))))))

(deftest graph-data-app-read-check-skips-the-bundle-test
  (testing "the graph endpoints check a data app start node without reading its bundle"
    (mt/with-premium-features #{:dependencies :data-apps}
      (mt/with-temp [:model/DataApp {app-id :id} {:name         "birds"
                                                  :display_name "Birds"
                                                  :bundle_path  "birds.js"
                                                  :bundle       (byte-array [1 2 3])}]
        (testing "a full row read counts"
          (is (seq (deps.test/data-app-bundle-reads #(t2/select-one :model/DataApp :id app-id)))))
        (doseq [endpoint ["ee/dependencies/graph" "ee/dependencies/graph/dependents" "ee/dependencies/graph/broken"]]
          (testing endpoint
            (is (= [] (deps.test/data-app-bundle-reads
                       #(mt/user-http-request :crowberto :get 200 endpoint :id app-id :type "data-app"))))))))))