/*
docker run -v ./script.js:/app/script.js --rm playwright:1.47.0
*/
import type { Page } from "playwright";

interface credentials {
  username: string;
  password: string;
}

async function goToInstallationPage(
  { page, dolibarrAddress }: { page: Page; dolibarrAddress: string },
): Promise<void> {
  await page.goto(`${dolibarrAddress}/install/`);
}

async function doFirstInstall(
  { page, dolibarrAddress, DBpassword, adminCredentials }: {
    page: Page;
    dolibarrAddress: string;
    DBpassword: string;
    adminCredentials: credentials;
  },
): Promise<void> {
  await goToInstallationPage({ page, dolibarrAddress });

  const beginFirstInstallBtn = page.locator(
    "table table table tr:last-of-type a.button",
  );
  await beginFirstInstallBtn.click();

  // 1
  await page.fill('input[name="db_pass"]', DBpassword);
  await page.click('input[type="submit"]');

  // 2 Migrations
  await page.click('input[type="submit"]', { timeout: 3600 * 1000 });

  // 3
  await page.uncheck('input[name="dolibarrpingno"]');
  await page.click('input[type="submit"]');

  await page.fill('input[name="login"]', adminCredentials.username);
  await page.fill('input[name="pass"]', adminCredentials.password);
  await page.fill('input[name="pass_verif"]', adminCredentials.password);
  await page.click('input[type="submit"]');
}

async function isUpgradeLocked(
  { page, dolibarrAddress }: { page: Page; dolibarrAddress: string },
): Promise<boolean> {
  await goToInstallationPage({ page, dolibarrAddress });
  return (
    await page.locator("table").count() === 0 &&
    await page.getByText("Cliquez ici pour aller sur votre application")
        .count() > 0
  );
}

export default {
  doFirstInstall,
  isUpgradeLocked,
};
