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

test('Create new project, then search for it', async ({ page }) => {
  // Generate a random string of 16 characters
  let randomString = Math.random().toString(36).substring(2, 18);

  // In case the string is shorter than 16 characters, generate more characters until it is 16 characters long
  while (randomString.length < 16) {
    randomString += Math.random().toString(36).substring(2, 18);
  }
  const finalRandomString = randomString.substring(0, 16);

  // Standard texts
  const standardTitle = "Idea ";
  const standardDescription = "Description of Idea ";

  // Combine texts with the random string
  const finalTitle = standardTitle + finalRandomString;
  const finalDescription = standardDescription + finalRandomString;

  // Import user 00
  await importUser(page, '00');

  // Pause for 5 seconds
  await page.waitForTimeout(5000); // I have to wait, otherwise the (+) button to add a new project doesn't appear

  // Create new project
  await page.goto('./projects');
  await page.getByRole('link', { name: 'Projects', exact: true }).click();
  await page.getByRole('button').click();
  await page.getByPlaceholder('Idea Name').fill(finalTitle); // Add random suffix
  await page.getByPlaceholder('Description').fill(finalDescription);
  await page.getByPlaceholder('Website').fill('https://example.com');
  await page.getByPlaceholder('Start Date').fill('2025-12-01');
  await page.getByPlaceholder('Start Time').fill('12:00');
  await page.getByRole('button', { name: 'Save Project' }).click();

  // Check texts
  await expect(page.locator('h2')).toContainText(finalTitle);
  await expect(page.locator('#Content')).toContainText(finalDescription);

  // Search for newly-created project in /projects
  await page.goto('./projects');
  await page.getByRole('link', { name: 'Projects', exact: true }).click();
  await page.waitForTimeout(3000); // Wait for a bit
  await expect(page.locator('ul#listProjects li.border-b:nth-child(1)')).toContainText(finalRandomString); // Assumes newest project always appears first in the Projects tab list

  // Search for newly-created project in /discover
  await page.goto('./discover');
  await page.waitForTimeout(3000); // Wait for a bit
  await page.getByPlaceholder('Search…').fill(finalRandomString);
  await page.locator('#QuickSearch button').click();
  await expect(page.locator('ul#listDiscoverResults li.border-b:nth-child(1)')).toContainText(finalRandomString);
});