// 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/apps/browser_instance/web_contents_instance_id_utils.h"

#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser_init_state.h"
#include "chrome/browser/ui/browser_window/public/browser_window_interface.h"
#include "chrome/browser/ui/browser_window/public/global_browser_collection.h"
#include "chrome/browser/ui/web_applications/app_browser_controller.h"
#include "chrome/browser/web_applications/mojom/user_display_mode.mojom.h"
#include "chrome/browser/web_applications/proto/web_app_install_state.pb.h"
#include "chrome/browser/web_applications/user_display_mode.h"
#include "chrome/browser/web_applications/web_app.h"
#include "chrome/browser/web_applications/web_app_filter.h"
#include "chrome/browser/web_applications/web_app_helpers.h"
#include "chrome/browser/web_applications/web_app_provider.h"
#include "chrome/browser/web_applications/web_app_registrar.h"
#include "components/webapps/common/web_app_id.h"
#include "content/public/browser/web_contents.h"
#include "extensions/browser/extension_registrar.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/launch_util.h"
#include "extensions/common/extension.h"

namespace apps {

namespace {

const extensions::Extension* GetExtensionForWebContents(
    Profile* profile,
    content::WebContents* tab) {
  extensions::ExtensionRegistrar* extension_registrar =
      extensions::ExtensionRegistrar::Get(profile);
  if (!extension_registrar || !extension_registrar->extensions_enabled()) {
    return nullptr;
  }

  auto* registry = extensions::ExtensionRegistry::Get(profile);
  const GURL url = tab->GetVisibleURL();
  const extensions::Extension* extension =
      registry->enabled_extensions().GetAppByURL(url);

  if (extension && !extensions::LaunchesInWindow(profile, extension)) {
    return extension;
  }
  return nullptr;
}

}  // namespace

std::optional<std::string> GetInstanceAppIdForWebContents(
    content::WebContents* tab) {
  Profile* profile = Profile::FromBrowserContext(tab->GetBrowserContext());
  // Note: It is possible to come here after a tab got removed from the browser
  // before it gets destroyed, in which case there is no browser.
  BrowserWindowInterface* browser =
      GlobalBrowserCollection::GetInstance()->FindBrowserWithTab(tab);

  // Use the Browser's app name to determine the web app for app windows and use
  // the tab's url for app tabs.
  if (auto* provider =
          web_app::WebAppProvider::GetForLocalAppsUnchecked(profile)) {
    if (browser) {
      web_app::AppBrowserController* app_controller =
          web_app::AppBrowserController::From(browser);
      if (app_controller) {
        return app_controller->app_id();
      }
    }

    std::optional<webapps::AppId> app_id =
        provider->registrar_unsafe().FindBestAppWithUrlInScope(
            tab->GetVisibleURL(), web_app::WebAppFilter::OpensInBrowserTab());
    if (app_id) {
      const web_app::WebApp* web_app =
          provider->registrar_unsafe().GetAppById(*app_id);
      DCHECK(web_app);
      if (web_app->user_display_mode() ==
              web_app::mojom::UserDisplayMode::kBrowser &&
          !web_app->is_uninstalling()) {
        return app_id;
      }
    }
  }

  // Use the Browser's app name.
  if (browser &&
      (browser->GetType() == BrowserWindowInterface::TYPE_APP ||
       browser->GetType() == BrowserWindowInterface::TYPE_APP_POPUP)) {
    return web_app::GetAppIdFromApplicationName(
        BrowserInitState::From(browser)->create_params().app_name);
  }

  const extensions::Extension* extension =
      GetExtensionForWebContents(profile, tab);
  if (extension) {
    return extension->id();
  }
  return std::nullopt;
}

}  // namespace apps
