import { Locator, expect as baseExpect } from '@playwright/test';

export const expect = baseExpect.extend({
  /**
   * Ensures the Locator resolves to a number of DOM nodes greater than the specified minimum treshold.
   *
   * **Usage**
   * ```ts
   * const alerts = page.getByRole('alert');
   * await expect(alerts).toHaveCountGreaterThan(0);
   * ```
   *
   * @param min Minimum treshold.
   * @param options
   */
  async toHaveCountGreaterThan(locator: Locator, min: number, options?: { timeout?: number }) {
    let pass = true;

    try {
      await baseExpect(locator.nth(min)).toBeVisible(options);
    } catch {
      pass = false;
    }

    const name = 'toHaveCountGreaterThan';
    const count = await locator.count();
    const message = pass
      ? () =>
          this.utils.matcherHint(name, 'locator', min, { isNot: this.isNot }) +
          '\n\n' +
          `Locator: ${locator}\n` +
          `Expected: <= ${this.utils.printExpected(min)}\n` +
          `Received: ${this.utils.printReceived(count)}`
      : () =>
          this.utils.matcherHint(name, 'locator', min, undefined) +
          '\n\n' +
          `Locator: ${locator}\n` +
          `Expected: > ${this.utils.printExpected(min)}\n` +
          `Received: ${this.utils.printReceived(count)}`;

    return {
      message,
      pass,
      name,
      expected: min,
      actual: count,
    };
  },
});
