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

export async function completeVipPayment(page: Page) {
  const checkoutButton = page.getByRole("button", { name: "Pay and Top Up" });
  await expect(checkoutButton).toBeEnabled();

  await checkoutButton.click();
  const renewalDialog = page.getByRole("dialog", {
    name: "Automatic Renewal Confirmation",
  });
  await expect(renewalDialog).toBeVisible();

  const createOrderRequestPromise = page.waitForRequest("**/api/payment/create-order");
  const orderStatusRequestPromise = page.waitForRequest("**/api/payment/order-status**");
  await renewalDialog.getByRole("button", { name: "Confirm" }).click();
  const createOrderRequest = await createOrderRequestPromise;
  expect(createOrderRequest.postDataJSON()).toMatchObject({ planId: "vip_monthly", payChannel: "stripe" });
  await orderStatusRequestPromise;
  const paymentSuccessDialog = page.getByRole("alertdialog", { name: "Payment successful" });
  await expect(paymentSuccessDialog).toBeVisible();
  await paymentSuccessDialog.getByRole("button", { name: "OK" }).click();
}

export async function expectVipChatSubscriptionUrl(page: Page) {
  await expect(page).toHaveURL(/\/subscription\?/);
  const url = new URL(page.url());
  expect(url.pathname).toBe("/subscription");
  expect(url.searchParams.get("type")).toBe("vip");
  expect(url.searchParams.get("returnTo")).toBe("chat");
}

export function expectAuthRedirectToVipChatSubscription(page: Page) {
  const redirect = new URL(page.url()).searchParams.get("redirect");
  expect(redirect).not.toBeNull();
  const redirectUrl = new URL(redirect ?? "", "http://e2e.local");
  expect(redirectUrl.pathname).toBe("/subscription");
  expect(redirectUrl.searchParams.get("type")).toBe("vip");
  expect(redirectUrl.searchParams.get("returnTo")).toBe("chat");
}
