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

import { apiEnvelope } from "../data/common";
import { checkoutHandoffResponse, emailLoginResponse, guestLoginResponse, refreshedEmailLoginResponse, refreshedGuestLoginResponse, topUpHandoffResponse } from "../data/auth";

export interface AuthMockState {
  chatSendTokenRefreshFlow: boolean;
  isChatSendTokenExpired: () => boolean;
  topUpHandoffFlow: boolean;
  checkoutHandoffFlow: boolean;
}

export async function registerAuthMocks(page: Page, state: AuthMockState) {
  await page.route("**/api/auth/handoff/checkout/consume", async (route) => {
    if (!state.checkoutHandoffFlow) {
      await route.continue();
      return;
    }
    await route.fulfill({ json: apiEnvelope(checkoutHandoffResponse) });
  });

  await page.route("**/api/auth/handoff/topup/consume", async (route) => {
    if (!state.topUpHandoffFlow) {
      await route.continue();
      return;
    }
    await route.fulfill({ json: apiEnvelope(topUpHandoffResponse) });
  });

  await page.route("**/api/auth/guest", async (route) => {
    const response = state.chatSendTokenRefreshFlow && state.isChatSendTokenExpired() ? refreshedGuestLoginResponse : guestLoginResponse;
    await route.fulfill({ json: apiEnvelope(response) });
  });
  await page.route("**/api/auth/login", async (route) => {
    await route.fulfill({ json: apiEnvelope(emailLoginResponse) });
  });
  await page.route("**/api/auth/refresh", async (route) => {
    await route.fulfill({ json: apiEnvelope(refreshedEmailLoginResponse) });
  });
  await page.route("**/api/auth/logout", async (route) => {
    await route.fulfill({ json: apiEnvelope(null) });
  });
}
