// 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 "chrome/browser/ui/webui/ash/cloud_upload/hats_office_trigger.h"

#include <string>

#include "ash/constants/ash_features.h"
#include "ash/constants/ash_switches.h"
#include "ash/constants/web_app_id_constants.h"
#include "base/check_deref.h"
#include "base/command_line.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/test_future.h"
#include "base/time/clock.h"
#include "base/time/time.h"
#include "base/unguessable_token.h"
#include "chrome/browser/apps/app_service/app_service_proxy.h"
#include "chrome/browser/apps/app_service/app_service_proxy_factory.h"
#include "chrome/browser/ash/hats/hats_config.h"
#include "chrome/browser/ash/hats/hats_notification_controller.h"
#include "chrome/browser/ash/login/users/fake_chrome_user_manager.h"
#include "chrome/browser/ash/profiles/profile_helper.h"
#include "chrome/browser/policy/profile_policy_connector.h"
#include "chrome/browser/safe_browsing/url_lookup_service_factory.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile_manager.h"
#include "chromeos/ash/components/browser_context_helper/browser_context_helper.h"
#include "chromeos/ash/components/network/network_handler.h"
#include "chromeos/ash/components/network/network_handler_test_helper.h"
#include "components/services/app_service/public/cpp/instance.h"
#include "components/session_manager/core/fake_session_manager_delegate.h"
#include "components/session_manager/core/session_manager.h"
#include "content/public/test/browser_task_environment.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/message_center/message_center.h"
#include "ui/message_center/test/message_center_waiter.h"

namespace ash::cloud_upload {

namespace {
constexpr char kFakeUserEmail[] = "test-user@example.com";
}  // namespace

class HatsOfficeTriggerTestBase : public testing::Test {
 public:
  HatsOfficeTriggerTestBase() {
    scoped_feature_list_.InitAndEnableFeature(kHatsOfficeSurvey.feature);

    base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
    command_line->AppendSwitchASCII(
        ash::switches::kForceHappinessTrackingSystem,
        ash::features::kHappinessTrackingOffice.name);
  }
  ~HatsOfficeTriggerTestBase() override = default;

  // testing::Test:
  void SetUp() override {
    user_manager_ = std::make_unique<FakeChromeUserManager>();
    user_manager_->Initialize();
    // Login user.
    user_manager_->AddUser(AccountId::FromUserEmail(kFakeUserEmail));
  }

  void TearDown() override {
    user_manager_->Destroy();
    user_manager_.reset();
  }

  bool IsDelayTriggerActive() {
    return hats_office_trigger_.IsDelayTriggerActiveForTesting();
  }

  bool IsAppStateTriggerActive() {
    return hats_office_trigger_.IsAppStateTriggerActiveForTesting();
  }

  const HatsNotificationController* GetHatsNotificationController() const {
    return hats_office_trigger_.GetHatsNotificationControllerForTesting();
  }

  base::Time Now() const { return task_environment_.GetMockClock()->Now(); }

  base::test::ScopedFeatureList scoped_feature_list_;
  content::BrowserTaskEnvironment task_environment_{
      base::test::TaskEnvironment::TimeSource::MOCK_TIME};
  session_manager::SessionManager session_manager_{
      std::make_unique<session_manager::FakeSessionManagerDelegate>()};
  std::unique_ptr<FakeChromeUserManager> user_manager_;

  HatsOfficeTrigger hats_office_trigger_;
};

class HatsOfficeTriggerTest : public HatsOfficeTriggerTestBase {
 public:
  void SetUp() override {
    HatsOfficeTriggerTestBase::SetUp();

    const AccountId account_id = AccountId::FromUserEmail(kFakeUserEmail);

    user_manager_->LoginUser(account_id);
    user_manager_->SwitchActiveUser(account_id);

    ASSERT_TRUE(test_profile_manager_.SetUp());
    // Use sign-in profile to simulate the login screen.
    profile_ = test_profile_manager_.CreateTestingProfile(kFakeUserEmail);
    session_manager_.SetSessionState(session_manager::SessionState::ACTIVE);

    message_center::MessageCenter::Initialize();
    network_handler_test_helper_ = std::make_unique<NetworkHandlerTestHelper>();

    task_environment_.RunUntilIdle();
  }

  void TearDown() override {
    // Remove the hats notification if it is showing. This allows the
    // scopedref-ed HatsNotificationController to get destroyed at the end of
    // the test.
    const user_manager::User& user = GetUserForProfile();
    const std::string notification_id = GetHatsNotificationId(user);
    if (IsHatsNotificationActive(notification_id)) {
      message_center::MessageCenter::Get()->RemoveNotification(
          notification_id, /*by_user=*/true);
    }
    network_handler_test_helper_.reset();
    profile_ = nullptr;
    test_profile_manager_.DeleteAllTestingProfiles();

    message_center::MessageCenter::Shutdown();
    HatsOfficeTriggerTestBase::TearDown();
  }

  bool IsHatsNotificationActive(const std::string& notification_id) const {
    return message_center::MessageCenter::Get()->FindVisibleNotificationById(
               notification_id) != nullptr;
  }

  std::string GetHatsNotificationId(const user_manager::User& user) const {
    return HatsNotificationController::GetMessageCenterNotificationIdForTesting(
        user);
  }

  const user_manager::User& GetUserForProfile() const {
    return CHECK_DEREF(
        BrowserContextHelper::Get()->GetUserByBrowserContext(profile_));
  }

  void OnTrackedDocsInstance(apps::InstanceState state) {
    apps::InstanceRegistry& registry =
        apps::AppServiceProxyFactory::GetForProfile(profile_)
            ->InstanceRegistry();
    auto instance = std::make_unique<apps::Instance>(
        ash::kGoogleDocsAppId, tracked_instance_id_, nullptr);
    instance->UpdateState(state, Now());
    registry.OnInstance(std::move(instance));
  }

  void OnIgnoredDocsInstance(apps::InstanceState state) {
    apps::InstanceRegistry& registry =
        apps::AppServiceProxyFactory::GetForProfile(profile_)
            ->InstanceRegistry();
    auto instance = std::make_unique<apps::Instance>(
        ash::kGoogleDocsAppId, ignored_instance_id_, nullptr);
    instance->UpdateState(state, Now());
    registry.OnInstance(std::move(instance));
  }

  TestingProfileManager test_profile_manager_{
      TestingBrowserProcess::GetGlobal()};
  raw_ptr<Profile> profile_ = nullptr;

  base::UnguessableToken tracked_instance_id_ =
      base::UnguessableToken::Create();
  base::UnguessableToken ignored_instance_id_ =
      base::UnguessableToken::Create();

  std::unique_ptr<NetworkHandlerTestHelper> network_handler_test_helper_;
};

class HatsOfficeTriggerLoginScreenTest : public HatsOfficeTriggerTestBase {
 public:
  void SetUp() override {
    HatsOfficeTriggerTestBase::SetUp();
    ash::ProfileHelper::Get();  // Instantiate ProfileHelper.
    session_manager_.SetSessionState(
        session_manager::SessionState::LOGIN_PRIMARY);
  }
};

TEST_F(HatsOfficeTriggerTest, ShowSurveyAfterDelaySuccess) {
  const user_manager::User& user = GetUserForProfile();
  const std::string notification_id = GetHatsNotificationId(user);
  ASSERT_FALSE(IsHatsNotificationActive(notification_id));

  message_center::MessageCenterWaiter waiter(notification_id);
  hats_office_trigger_.ShowSurveyAfterDelay(
      HatsOfficeLaunchingApp::kQuickOffice);

  ASSERT_TRUE(IsDelayTriggerActive());
  ASSERT_FALSE(IsHatsNotificationActive(notification_id));
  ASSERT_FALSE(GetHatsNotificationController());

  // This test previously passed incorrectly due to a latent bug. The core of
  // the issue is that this test fixture uses a mock clock
  // (`TimeSource::MOCK_TIME`), meaning time does not advance unless explicitly
  // told to. The function under test, `ShowSurveyAfterDelay`, schedules the
  // survey notification to appear after a delay via a `base::OneShotTimer`.
  //
  // The previous test implementation used waiters (`TestFuture` or a
  // `MessageCenterWaiter` backed by `base::RunLoop`) that, in this specific
  // test environment, caused the timer's task to be flushed and run
  // immediately, ignoring the intended delay. This resulted in a consistent
  // "false positive" pass, as the test was not actually verifying the delay.
  //
  // The current `MessageCenterWaiter` uses `base::test::RunUntil`, a modern
  // testing utility that correctly respects mock time and has a built-in
  // timeout to detect hangs. This waiter correctly revealed the test's flaw.
  // Therefore, we MUST manually advance the clock with `FastForwardBy` to
  // trigger the timer and allow the test to pass correctly.
  task_environment_.FastForwardBy(kDelayTriggerTimeout);
  waiter.WaitUntilAdded();

  ASSERT_FALSE(IsDelayTriggerActive());
  ASSERT_TRUE(GetHatsNotificationController());
  ASSERT_TRUE(IsHatsNotificationActive(notification_id));
}

TEST_F(HatsOfficeTriggerTest, ShowSurveyAfterAppInactiveSuccess) {
  const user_manager::User& user = GetUserForProfile();
  const std::string notification_id = GetHatsNotificationId(user);
  ASSERT_FALSE(IsHatsNotificationActive(notification_id));
  ASSERT_FALSE(GetHatsNotificationController());

  message_center::MessageCenterWaiter waiter(notification_id);
  hats_office_trigger_.ShowSurveyAfterAppInactive(
      ash::kGoogleDocsAppId, HatsOfficeLaunchingApp::kDrive);

  // Simulate receiving updates from an instance that shouldn't be tracked.
  OnIgnoredDocsInstance(
      apps::InstanceState(apps::kStarted | apps::kRunning | apps::kVisible));
  task_environment_.FastForwardBy(kDebounceDelay);
  // Simulate receiving instance updates. The first few updates, when the app is
  // not "active" yet, should be debounced.
  OnTrackedDocsInstance(apps::InstanceState(apps::kStarted | apps::kRunning));
  task_environment_.FastForwardBy(kDebounceDelay / 2);
  OnTrackedDocsInstance(
      apps::InstanceState(apps::kStarted | apps::kRunning | apps::kVisible));
  task_environment_.FastForwardBy(kDebounceDelay / 2);

  ASSERT_FALSE(IsHatsNotificationActive(notification_id));
  ASSERT_FALSE(GetHatsNotificationController());

  // Simulate the app being active. The survey shouldn't be triggered.
  OnTrackedDocsInstance(apps::InstanceState(apps::kStarted | apps::kRunning |
                                            apps::kVisible | apps::kActive));
  task_environment_.FastForwardBy(kDebounceDelay);

  ASSERT_FALSE(IsHatsNotificationActive(notification_id));
  ASSERT_FALSE(GetHatsNotificationController());

  // Simulate another update from the app that isn't tracked, it shouldn't
  // trigger the survey either.
  OnIgnoredDocsInstance(
      apps::InstanceState(apps::kStarted | apps::kRunning | apps::kVisible));
  task_environment_.FastForwardBy(kDebounceDelay);

  ASSERT_FALSE(IsHatsNotificationActive(notification_id));
  ASSERT_FALSE(GetHatsNotificationController());

  // Simulate the app being no longer active, it will this time trigger the
  // survey.
  OnTrackedDocsInstance(
      apps::InstanceState(apps::kStarted | apps::kRunning | apps::kVisible));

  task_environment_.FastForwardBy(kDebounceDelay);
  waiter.WaitUntilAdded();

  ASSERT_TRUE(GetHatsNotificationController());
  ASSERT_TRUE(IsHatsNotificationActive(notification_id));
}

TEST_F(HatsOfficeTriggerTest, NoAppUpdateTimeout) {
  const user_manager::User& user = GetUserForProfile();
  const std::string notification_id = GetHatsNotificationId(user);
  ASSERT_FALSE(IsAppStateTriggerActive());
  ASSERT_FALSE(IsHatsNotificationActive(notification_id));
  ASSERT_FALSE(GetHatsNotificationController());

  hats_office_trigger_.ShowSurveyAfterAppInactive(
      ash::kGoogleDocsAppId, HatsOfficeLaunchingApp::kDrive);

  ASSERT_TRUE(IsAppStateTriggerActive());

  // The expected initial app event (started and running) isn't received during
  // the initial delay.
  OnTrackedDocsInstance(apps::kStarted);
  task_environment_.FastForwardBy(kFirstAppStateEventTimeout);

  ASSERT_FALSE(IsAppStateTriggerActive());
  ASSERT_FALSE(IsHatsNotificationActive(notification_id));
  ASSERT_FALSE(GetHatsNotificationController());

  // Simulate receiving the expected instance updates. They shouldn't trigger
  // the survey.
  OnTrackedDocsInstance(apps::InstanceState(apps::kStarted | apps::kRunning));
  task_environment_.FastForwardBy(kDebounceDelay / 2);
  // Running and active.
  OnTrackedDocsInstance(apps::InstanceState(apps::kStarted | apps::kRunning |
                                            apps::kVisible | apps::kActive));
  task_environment_.FastForwardBy(kDebounceDelay * 2);
  // Destroyed.
  OnTrackedDocsInstance(apps::kDestroyed);
  task_environment_.FastForwardBy(kDebounceDelay);

  ASSERT_FALSE(IsHatsNotificationActive(notification_id));
  ASSERT_FALSE(GetHatsNotificationController());
}

TEST_F(HatsOfficeTriggerTest, ShowSurveyOnlyOnce) {
  const user_manager::User& user = GetUserForProfile();
  const std::string notification_id = GetHatsNotificationId(user);
  ASSERT_FALSE(IsHatsNotificationActive(notification_id));

  // Show survey once
  message_center::MessageCenterWaiter waiter(notification_id);

  hats_office_trigger_.ShowSurveyAfterDelay(
      HatsOfficeLaunchingApp::kQuickOfficeClippyOff);

  ASSERT_TRUE(IsDelayTriggerActive());
  ASSERT_FALSE(IsHatsNotificationActive(notification_id));
  ASSERT_FALSE(GetHatsNotificationController());

  // This test previously passed incorrectly due to a latent bug. The core of
  // the issue is that this test fixture uses a mock clock
  // (`TimeSource::MOCK_TIME`), meaning time does not advance unless explicitly
  // told to. The function under test, `ShowSurveyAfterDelay`, schedules the
  // survey notification to appear after a delay via a `base::OneShotTimer`.
  //
  // The previous test implementation used waiters (`TestFuture` or a
  // `MessageCenterWaiter` backed by `base::RunLoop`) that, in this specific
  // test environment, caused the timer's task to be flushed and run
  // immediately, ignoring the intended delay. This resulted in a consistent
  // "false positive" pass, as the test was not actually verifying the delay.
  //
  // The current `MessageCenterWaiter` uses `base::test::RunUntil`, a modern
  // testing utility that correctly respects mock time and has a built-in
  // timeout to detect hangs. This waiter correctly revealed the test's flaw.
  // Therefore, we MUST manually advance the clock with `FastForwardBy` to
  // trigger the timer and allow the test to pass correctly.
  task_environment_.FastForwardBy(kDelayTriggerTimeout);
  waiter.WaitUntilAdded();

  ASSERT_FALSE(IsDelayTriggerActive());
  const HatsNotificationController* hats_notification_controller =
      GetHatsNotificationController();
  EXPECT_NE(hats_notification_controller, nullptr);
  ASSERT_TRUE(IsHatsNotificationActive(notification_id));

  // Trigger survey again but the controller shouldn't be a new instance.
  hats_office_trigger_.ShowSurveyAfterDelay(HatsOfficeLaunchingApp::kDrive);

  ASSERT_FALSE(IsDelayTriggerActive());
  EXPECT_EQ(hats_notification_controller, GetHatsNotificationController());
}

TEST_F(HatsOfficeTriggerLoginScreenTest, NoActiveUser) {
  hats_office_trigger_.ShowSurveyAfterDelay(HatsOfficeLaunchingApp::kMS365);
  ASSERT_FALSE(IsDelayTriggerActive());
  ASSERT_FALSE(GetHatsNotificationController());
}

TEST_F(HatsOfficeTriggerTest, NoSurveyForManagedProfile) {
  const user_manager::User& user = GetUserForProfile();
  const std::string notification_id = GetHatsNotificationId(user);
  profile_->GetProfilePolicyConnector()->OverrideIsManagedForTesting(true);
  ASSERT_FALSE(IsHatsNotificationActive(notification_id));

  hats_office_trigger_.ShowSurveyAfterDelay(HatsOfficeLaunchingApp::kMS365);
  ASSERT_FALSE(IsDelayTriggerActive());
  ASSERT_FALSE(GetHatsNotificationController());
}

TEST_F(HatsOfficeTriggerTest, NoSurveyIfSessionNotActive) {
  const user_manager::User& user = GetUserForProfile();
  const std::string notification_id = GetHatsNotificationId(user);
  session_manager::SessionManager::Get()->SetSessionState(
      session_manager::SessionState::LOCKED);
  ASSERT_FALSE(IsHatsNotificationActive(notification_id));

  hats_office_trigger_.ShowSurveyAfterDelay(HatsOfficeLaunchingApp::kMS365);

  ASSERT_TRUE(IsDelayTriggerActive());
  task_environment_.FastForwardBy(kDelayTriggerTimeout);
  ASSERT_FALSE(IsDelayTriggerActive());
  ASSERT_FALSE(GetHatsNotificationController());
}

}  // namespace ash::cloud_upload
