import type { Locator, Page } from "playwright";

/** 统一 browser evaluate / waitForFunction 入口；禁止模块外直接 page.evaluate */
export class ExecutionLayer {
  constructor(private readonly page: Page) {}

  static forPage(page: Page): ExecutionLayer {
    return new ExecutionLayer(page);
  }

  getPage(): Page {
    return this.page;
  }

  async evaluateOnPage<T>(script: string, arg?: unknown): Promise<T> {
    if (arg === undefined) {
      return this.page.evaluate(script) as Promise<T>;
    }
    return this.page.evaluate(script, arg) as Promise<T>;
  }

  async evaluateOnLocator<T>(
    locator: Locator,
    script: string,
    arg?: unknown,
  ): Promise<T> {
    if (arg === undefined) {
      return locator.evaluate(script) as Promise<T>;
    }
    return locator.evaluate(script, arg) as Promise<T>;
  }

  async waitForBrowserFunction(
    script: string,
    arg: unknown,
    timeoutMs: number,
  ): Promise<void> {
    await this.page.waitForFunction(script, arg, { timeout: timeoutMs });
  }
}
