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

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

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

test("guest can unlock a paid image after email login and subscription payment", async ({
  page,
}) => {
  await enterChatFromSplash(page);
  await dismissChatInterruptions(page);

  const messageInput = page.getByRole("textbox", { name: "Message" });
  await expect(messageInput).toBeVisible({ timeout: 10_000 });
  await messageInput.fill("给我发图片");

  const sendRequestPromise = page.waitForRequest("**/api/chat/send");
  await messageInput.press("Enter");

  const sendRequest = await sendRequestPromise;
  expect(sendRequest.postDataJSON()).toMatchObject({
    message: "给我发图片",
  });

  const paidImageButton = page.getByRole("button", {
    name: "Open image in fullscreen",
  }).last();
  await expect(paidImageButton).toBeVisible();

  await paidImageButton.click();
  await expect(page).toHaveURL(new RegExp(`/chat/image/${paidImageMessageId}$`));

  const lockedImageDialog = page.getByRole("dialog", {
    name: "Locked fullscreen image",
  });
  await expect(lockedImageDialog).toBeVisible();

  await lockedImageDialog
    .getByRole("button", { name: "Unlock high-definition large image" })
    .click();

  await expect(page).toHaveURL(/\/auth\?redirect=/);
  expect(new URL(page.url()).searchParams.get("redirect")).toBe(
    `/chat/image/${paidImageMessageId}`,
  );

  await switchToEmailSignIn(page);
  const unlockRequestPromise = page.waitForRequest(
    "**/api/chat/unlock-private",
  );
  await submitEmailLogin(page, {
    expectedUrl: new RegExp(`/chat/image/${paidImageMessageId}$`),
  });

  const unlockRequest = await unlockRequestPromise;
  expect(unlockRequest.postDataJSON()).toMatchObject({
    messageId: paidImageMessageId,
  });

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

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

  await expect(page).toHaveURL(new RegExp(`/chat/image/${paidImageMessageId}$`));
});
