// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ash/webui/boca_ui/provider/tab_info_collector.h"

#include <memory>
#include <optional>

#include "ash/constants/ash_features.h"
#include "ash/shell.h"
#include "ash/webui/boca_ui/mojom/boca.mojom-shared.h"
#include "ash/webui/boca_ui/mojom/boca.mojom.h"
#include "base/functional/bind.h"
#include "base/test/bind.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window/public/create_browser_window.h"
#include "chrome/browser/ui/browser_window/public/global_browser_collection.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "chromeos/ash/components/boca/proto/bundle.pb.h"
#include "content/public/browser/web_ui.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "partition_alloc/pointers/raw_ptr.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/views/widget/any_widget_observer.h"

using ::testing::_;
using ::testing::Mock;
using ::testing::Return;
using ::testing::StrictMock;

namespace {
constexpr char kTabUrl1[] = "https://foo/1";
constexpr char kTabUrl2[] = "https://foo/2";
constexpr char kTabUrl3[] = "https://foo/3";
constexpr char kTabUrl4[] = "https://foo/4";

constexpr char kDefaultTitle[] = "foo";

}  // namespace

namespace ash::boca {

class TabInfoCollectorTest : public InProcessBrowserTest {
 public:
  TabInfoCollectorTest() = default;
  TabInfoCollectorTest(const TabInfoCollectorTest&) = delete;
  TabInfoCollectorTest operator=(const TabInfoCollectorTest&) = delete;
  ~TabInfoCollectorTest() override = default;

  Browser* CreateBrowser(const std::vector<GURL>& urls) {
    BrowserWindowCreateParams params(ProfileManager::GetActiveUserProfile(),
                                     /*from_user_gesture=*/false);
    Browser* browser =
        CreateBrowserWindow(std::move(params))->GetBrowserForMigrationOnly();
    // Create a new tab and make sure the urls have loaded.
    for (const auto& url : urls) {
      ui_test_utils::NavigateToURLWithDisposition(
          browser, url, WindowOpenDisposition::NEW_FOREGROUND_TAB,
          ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);
    }
    return browser;
  }


  void TearDown() override {
    tab_info_collector_.reset();
  }

  TabInfoCollector* tab_info_collector() { return tab_info_collector_.get(); }

 protected:
  auto GetUrlTypeCallback(
      std::optional<mojom::UrlType> url_type = std::nullopt) {
    return base::BindRepeating(
        [](std::optional<mojom::UrlType> url_type_param,
           int32_t) -> std::optional<mojom::UrlType> { return url_type_param; },
        url_type);
  }

  base::test::ScopedFeatureList scoped_feature_list_;
  std::unique_ptr<TabInfoCollector> tab_info_collector_;
};

class TabInfoCollectorConsumerTest : public TabInfoCollectorTest {
  void SetUp() override {
    scoped_feature_list_.InitWithFeatures(
        {ash::features::kBoca, ash::features::kBocaConsumer,
         ash::features::kOnDeviceSpeechRecognition},
        /*disabled_features=*/{});
    tab_info_collector_ = TabInfoCollector::Create(/*is_producer=*/false);
    TabInfoCollectorTest::SetUp();
  }
};

class TabInfoCollectorProducerTest : public TabInfoCollectorTest {
  void SetUp() override {
    scoped_feature_list_.InitWithFeatures(
        {ash::features::kBoca, ash::features::kOnDeviceSpeechRecognition},
        /*disabled_features=*/{});
    tab_info_collector_ = TabInfoCollector::Create(/*is_producer=*/true);
    TabInfoCollectorTest::SetUp();
  }
};

IN_PROC_BROWSER_TEST_F(TabInfoCollectorProducerTest,
                       GetTabListForProducerNonEmptyWindow) {
  ASSERT_EQ(1u, GlobalBrowserCollection::GetInstance()->GetSize());

  // Create browser 1 and navigate to url1 and then url2
  CreateBrowser({GURL(kTabUrl1), GURL(kTabUrl2)});

  // Create browser 2 and navigate to url3
  CreateBrowser({GURL(kTabUrl3)});

  // Create browser 3 and navigate to url4
  CreateBrowser({GURL(kTabUrl4)});

  auto window_list =
      tab_info_collector()->GetWindowTabInfo(GetUrlTypeCallback());

  // Start with 1 existing window.
  ASSERT_EQ(4u, window_list.size());

  // Verify window is listed in non-ascending order based on last access time.
  ASSERT_EQ(1u, window_list[0]->tab_list.size());
  ASSERT_EQ(1u, window_list[1]->tab_list.size());
  ASSERT_EQ(2u, window_list[2]->tab_list.size());
  // Preexisting window.
  ASSERT_EQ(1u, window_list[3]->tab_list.size());

  // Verify tab is listed in non-ascending order inside window based on last
  // access time.
  EXPECT_EQ(kTabUrl2, window_list[2]->tab_list[0]->url);
  EXPECT_EQ(kTabUrl1, window_list[2]->tab_list[1]->url);

  EXPECT_EQ(kTabUrl4, window_list[0]->tab_list[0]->url);
  EXPECT_EQ(kTabUrl3, window_list[1]->tab_list[0]->url);

  // Verify title is set
  EXPECT_EQ(kDefaultTitle, window_list[2]->tab_list[0]->title);
  EXPECT_EQ(kDefaultTitle, window_list[2]->tab_list[1]->title);
  EXPECT_EQ(kDefaultTitle, window_list[0]->tab_list[0]->title);
  EXPECT_EQ(kDefaultTitle, window_list[1]->tab_list[0]->title);
}

IN_PROC_BROWSER_TEST_F(TabInfoCollectorProducerTest,
                       GetTabListForProducerEmptyWindow) {
  // Close the browser and verify that all browser windows are closed.
  CloseBrowserSynchronously(browser());
  ASSERT_EQ(0u, GlobalBrowserCollection::GetInstance()->GetSize());

  auto window_list =
      tab_info_collector()->GetWindowTabInfo(GetUrlTypeCallback());

  EXPECT_EQ(0u, window_list.size());
}

IN_PROC_BROWSER_TEST_F(TabInfoCollectorProducerTest,
                       GetTabListForProducerIncognitoWindow) {
  CreateIncognitoBrowser(ProfileManager::GetActiveUserProfile());
  ASSERT_EQ(2u, GlobalBrowserCollection::GetInstance()->GetSize());

  auto window_list =
      tab_info_collector()->GetWindowTabInfo(GetUrlTypeCallback());

  EXPECT_EQ(1u, window_list.size());
}

IN_PROC_BROWSER_TEST_F(TabInfoCollectorConsumerTest,
                       GetTabListForTargetWindow) {
  ASSERT_EQ(1u, GlobalBrowserCollection::GetInstance()->GetSize());
  views::AnyWidgetObserver observer(views::test::AnyWidgetTestPasskey{});
  observer.set_shown_callback(
      base::BindLambdaForTesting([&](views::Widget* widget) {
        auto* window = widget->GetNativeWindow();
        auto window_list = tab_info_collector()->GetWindowTabInfoForTarget(
            window, GetUrlTypeCallback(mojom::UrlType::kGeminiGuidedLearning));

        // Only target window should be recorded.
        ASSERT_EQ(1u, window_list.size());

        ASSERT_EQ(1u, window_list[0]->tab_list.size());

        // Verify tab is listed in non-ascending order inside window based on
        // last access time.
        EXPECT_EQ(kTabUrl1, window_list[0]->tab_list[0]->url);
        EXPECT_EQ(mojom::UrlType::kGeminiGuidedLearning,
                  window_list[0]->tab_list[0]->url_type);
      }));

  // Create browser 1 and navigate to url1 and then url2
  CreateBrowser({GURL(kTabUrl1)});
}

}  // namespace ash::boca
