import { expect, test } from "@playwright/test";

import { mockCoreApis } from "@e2e/fixtures/api-mocks";
import {
  clearBrowserState,
  completeVipPayment,
  defaultCharacterChatUrl,
  expectInsufficientCreditsDialog,
  expectVipChatSubscriptionUrl,
  submitEmailLogin,
  switchToEmailSignIn,
} from "@e2e/fixtures/test-helpers";

test.beforeEach(async ({ baseURL, context, page }) => {
  await clearBrowserState(context, page, baseURL);
  await mockCoreApis(page, {
    paidImageInsufficientCreditsFlow: true,
  });
});

test("guest unlocks a promoted image through email login and top-up", async ({
  page,
}) => {
  await page.goto(
    "/external-entry?target=chat&mode=promotion&promotion_type=image",
  );
  await expect(page).toHaveURL(defaultCharacterChatUrl);

  const unlockButton = page.getByRole("button", {
    name: "Unlock private image",
  });
  await expect(unlockButton).toBeVisible({ timeout: 10_000 });

  await unlockButton.click();
  await expect(page).toHaveURL(/\/auth\?redirect=/);

  await switchToEmailSignIn(page);
  const unlockRequestPromise = page.waitForRequest(
    "**/api/chat/unlock-private",
  );
  await submitEmailLogin(page, { expectedUrl: defaultCharacterChatUrl });

  const unlockRequest = await unlockRequestPromise;
  expect(unlockRequest.method()).toBe("POST");
  expect(unlockRequest.postDataJSON()).toMatchObject({
    lockType: "image_paywall",
  });

  const insufficientCreditsDialog = await expectInsufficientCreditsDialog(page);
  await insufficientCreditsDialog
    .getByRole("button", { name: "Top up now" })
    .click();

  await expectVipChatSubscriptionUrl(page);
  await completeVipPayment(page);

  await expect(page).toHaveURL(defaultCharacterChatUrl);
  await expect(page.getByRole("textbox", { name: "Message" })).toBeVisible();
});
