import {
  test as setup,
  expect,
  authFilesRootDir,
  authFileForUser,
} from "../fixtures";
import {
  PRIVATE_KEY_SMALL_USER,
  SEED_PHRASE_12_USER,
  SEED_PHRASE_24_USER,
} from "../test-data";
import {
  enterPasswordsDuringOnboarding,
  selectWalletDuringOnboarding,
} from "../pages/password";
import { typeSeedPhrase } from "../pages/phrase";
import * as fs from "fs";

setup.beforeAll(() => {
  if (!fs.existsSync(authFilesRootDir)) {
    try {
      fs.mkdirSync(authFilesRootDir);
    } catch (err) {
      // mkdir can fail due to concurrency, and we ignore the error
    }
  }
});

const userContexts = [
  SEED_PHRASE_12_USER,
  SEED_PHRASE_24_USER,
  PRIVATE_KEY_SMALL_USER,
];

userContexts.forEach((user) => {
  setup(
    `authenticate for ${user.fileNameInCache}`,
    async ({ extensionPage: extPage, appType }) => {
      console.log(`Authenticating for ${appType}`);

      // Get to the password screen
      if (user.onboardingMethod === "import-private-key") {
        await extPage.getByText("Using a Private key").click();
        await extPage
          .locator('[placeholder="Enter or Paste your private key"]')
          .fill(user.privateKey);
        await extPage.getByText("Import Wallet").click();
      } else if (user.onboardingMethod === "import-seed-phrase-12") {
        await extPage.getByText("Using a recovery phrase").click();
        await typeSeedPhrase(extPage, user.phrase, { hasInputInFocus: true });
        await extPage.getByText("Import Wallet").click();
        await extPage.getByText("Show more wallets").click();
        const selectedWallets = user.wallets.filter((w) => w.isSelected);
        for (let wallet of selectedWallets) {
          await selectWalletDuringOnboarding(extPage, wallet.name);
        }
        await extPage.getByText("Proceed", { exact: true }).click();
      } else if (user.onboardingMethod === "import-seed-phrase-24") {
        await extPage.getByText("Using a recovery phrase").click();
        await extPage.getByRole("button", { name: "words arrow down" }).click();
        await extPage.getByText("24 words", { exact: true }).click();
        await typeSeedPhrase(extPage, user.phrase, { hasInputInFocus: false });
        await extPage.getByText("Import Wallet").click();
        await extPage.getByText("Show more wallets").click();
        const selectedWallets = user.wallets.filter((w) => w.isSelected);
        for (let wallet of selectedWallets) {
          await selectWalletDuringOnboarding(extPage, wallet.name);
        }
        await extPage.getByText("Proceed", { exact: true }).click();
      }

      await enterPasswordsDuringOnboarding(extPage);
      const successMessage =
        appType === "compass"
          ? "Your Compass wallet is ready!"
          : "Launch Extension";
      await expect(extPage.getByText(successMessage)).toBeVisible({
        timeout: 30_000,
      });

      // Save authentication state
      const context = extPage.context();
      let [background] = context.serviceWorkers();
      const storage: string = await background.evaluate(() => {
        return new Promise((resolve) => {
          // @ts-ignore
          // eslint-disable-next-line no-undef
          chrome.storage.local.get((items) => {
            resolve(JSON.stringify(items));
          });
        });
      });
      fs.writeFileSync(authFileForUser(user), storage);
    },
  );
});
