import { test, expect, Page } from '@playwright/test';
import { importUser } from './testUtils';

async function testProjectGive(page: Page, selector: string) {

  // Generate a random string of a few characters
  const randomString = Math.random().toString(36).substring(2, 6);

  // Generate a random non-zero single-digit number
  const randomNonZeroNumber = Math.floor(Math.random() * 99) + 1;

  // Standard title prefix
  const standardTitle = 'Gift ';

  // Combine title prefix with the random string
  const finalTitle = standardTitle + randomString;

  // find a project and enter a give to it and see that it shows
  await importUser(page, '00');
  await page.goto('./discover');
  await page.getByTestId('closeOnboardingAndFinish').click();

  await page.locator('ul#listDiscoverResults li:first-child a').click()
  // wait for the project page to load
  await page.waitForLoadState('networkidle');
  // click the give button, inside the first div
  await page.getByTestId(selector).locator('div:first-child div button').click();
  await page.getByPlaceholder('What was given').fill(finalTitle);
  await page.getByRole('spinbutton').fill(randomNonZeroNumber.toString());
  await page.getByRole('button', { name: 'Sign & Send' }).click();
  await expect(page.getByText('That gift was recorded.')).toBeVisible();
  await page.locator('div[role="alert"] button > svg.fa-xmark').click(); // dismiss info alert

  // refresh the page
  await page.reload();
  // check that the give is in the list
  await page
    .getByTestId(selector)
    .locator('div ul li:first-child')
    .filter({ hasText: finalTitle })
    .isVisible();
}

test('Record a give to a project', async ({ page }) => {
  await testProjectGive(page, 'gives-to');
});

test('Record a give from a project', async ({ page }) => {
  await testProjectGive(page, 'gives-from');
});