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

import {
  apiEnvelope,
  chatSendResponse,
  createPaymentOrderResponse,
  createChatSendResponse,
  createWeeklyLimitChatSendResponse,
  e2eEmailUser,
  emptyChatHistoryResponse,
  emailLoginResponse,
  guestLoginResponse,
  paidPaymentOrderStatusResponse,
  paymentPlansResponse,
  userEntitlementsResponse,
  vipStatusResponse,
} from "./test-data";

interface MockCoreApisOptions {
  chatLimitTriggerAt?: number;
}

export async function mockCoreApis(
  page: Page,
  options: MockCoreApisOptions = {},
): Promise<void> {
  const { chatLimitTriggerAt } = options;
  let sendCount = 0;

  await page.route("**/api/auth/guest", async (route) => {
    await route.fulfill({ json: apiEnvelope(guestLoginResponse) });
  });

  await page.route("**/api/auth/login", async (route) => {
    await route.fulfill({ json: apiEnvelope(emailLoginResponse) });
  });

  await page.route("**/api/auth/logout", async (route) => {
    await route.fulfill({ json: apiEnvelope(null) });
  });

  await page.route("**/api/user/profile", async (route) => {
    await route.fulfill({ json: apiEnvelope(e2eEmailUser) });
  });

  await page.route("**/api/user/entitlements", async (route) => {
    await route.fulfill({ json: apiEnvelope(userEntitlementsResponse) });
  });

  await page.route("**/api/chat/history**", async (route) => {
    await route.fulfill({ json: apiEnvelope(emptyChatHistoryResponse) });
  });

  await page.route("**/api/chat/send", async (route) => {
    sendCount += 1;

    const response =
      chatLimitTriggerAt != null && sendCount >= chatLimitTriggerAt
        ? createWeeklyLimitChatSendResponse(sendCount, chatLimitTriggerAt)
        : chatLimitTriggerAt != null
          ? createChatSendResponse(sendCount)
          : chatSendResponse;

    await route.fulfill({ json: apiEnvelope(response) });
  });

  await page.route("**/api/payment/plans**", async (route) => {
    await route.fulfill({ json: apiEnvelope(paymentPlansResponse) });
  });

  await page.route("**/api/payment/create-order", async (route) => {
    await route.fulfill({ json: apiEnvelope(createPaymentOrderResponse) });
  });

  await page.route("**/api/payment/order-status**", async (route) => {
    await route.fulfill({ json: apiEnvelope(paidPaymentOrderStatusResponse) });
  });

  await page.route("**/api/payment/vip-status**", async (route) => {
    await route.fulfill({ json: apiEnvelope(vipStatusResponse) });
  });
}
