/**
 * @file Bulk Gift Recording Test Suite
 * @description Tests TimeSafari's gift recording functionality under load by creating 
 * multiple gift records in sequence. Limited to 9 gifts to stay under 30-second timeout.
 * 
 * This test verifies:
 * 1. Scalability
 *    - System handles multiple gift recordings (9)
 *    - Performance remains stable across iterations
 *    - No data corruption during bulk operations
 * 
 * 2. Data Integrity
 *    - Each gift has unique identifiers
 *    - All gifts properly stored and retrievable
 *    - No cross-contamination between gift data
 * 
 * 3. UI/UX Stability
 *    - Interface remains responsive during bulk operations
 *    - Success notifications display correctly
 *    - Alert dismissal works consistently
 * 
 * Test Flow:
 * 1. Setup Phase
 *    - Generate arrays of unique strings for titles
 *    - Generate array of random numbers for amounts
 *    - Import User 00 (test account)
 * 
 * 2. Bulk Recording (9 iterations)
 *    - Navigate to home
 *    - Handle first-time onboarding dialog
 *    - Select recipient (Unnamed/Unknown)
 *    - Fill gift details from arrays
 *    - Sign and submit
 *    - Verify success
 *    - Dismiss notification
 *    - Verify gift in list
 * 
 * Test Data:
 * - Gift Count: 9 (optimized for timeout limits)
 * - Title Format: "Gift [unique-string]"
 * - Amount: Random numbers array
 * - Recipient: "Unnamed/Unknown" (constant)
 * 
 * Key Selectors:
 * - Gift input: '[placeholder="What was given"]'
 * - Amount input: '[role="spinbutton"]'
 * 
 */
import path from 'path';
import { test, expect } from '@playwright/test';
import { importUserAndCloseOnboarding } from './testUtils';

/**
 * Note: by default, this test uses the test image API server.
 *
 * If you want to use your own image API server, you can set the
 * VITE_DEFAULT_IMAGE_API_SERVER environment variable to your server's URL
 * in the playwright.config-local.ts file.
 * 
 */
test('Record item given from image-share', async ({ page }) => {

  let randomString = Math.random().toString(36).substring(2, 8);

  // Combine title prefix with the random string
  const finalTitle = `Gift ${randomString} from image-share`;

  await importUserAndCloseOnboarding(page, '00');

  // Record something given
  await page.goto('./test');

  const fileChooserPromise = page.waitForEvent('filechooser');
  await page.getByTestId('fileInput').click();
  const fileChooser = await fileChooserPromise;
  await fileChooser.setFiles(path.join(__dirname, '..', 'public', 'img', 'icons', 'android-chrome-192x192.png'));
  await page.getByTestId('fileUploadButton').click();

  // on shared photo page, choose the gift option
  await page.getByRole('button').filter({ hasText: /gift/i }).click();

  await page.getByTestId('imagery').getByRole('img').isVisible();
  await page.getByPlaceholder('What was received').fill(finalTitle);
  await page.getByRole('spinbutton').fill('2');
  await page.getByRole('button', { name: 'Sign & Send' }).click();

  // const recorded = await page.getByText('That gift was recorded.');
  await expect(await page.getByText('That gift was recorded.')).toBeVisible();
  await page.locator('div[role="alert"] button > svg.fa-xmark').click(); // dismiss info alert

  // Refresh home view and check gift
  await page.goto('./');
  const item1 = page.locator('li').filter({ hasText: finalTitle });
  await expect(item1.getByRole('img')).toBeVisible();
});

// // I believe there's a way to test this service worker feature.
// // The following is what I got from ChatGPT. I wonder if it doesn't work because it's not registering the service worker correctly.
//
// test('Trigger a photo-sharing fetch event in service worker with POST to /share-target', async ({ page }) => {
//   await importUser(page, '00');
//
//   // Create a FormData object with a photo
//   const photoPath = path.join(__dirname, '..', 'public', 'img', 'icons', 'android-chrome-192x192.png');
//   const photoContent = await fs.readFileSync(photoPath);
//   const [response] = await Promise.all([
//     page.waitForResponse(response => response.url().includes('/share-target')), // also check for response.status() === 303 ?
//     page.evaluate(async (photoContent) => {
//       const formData = new FormData();
//       formData.append('photo', new Blob([photoContent], { type: 'image/png' }), 'test-photo.jpg');
//
//       const response = await fetch('/share-target', {
//         method: 'POST',
//         body: formData,
//       });
//
//       return response;
//     }, photoContent)
//   ]);
//
//   // Verify the response redirected to /shared-photo
//   //expect(response.status).toBe(303);
//   console.log('response headers', response.headers());
//   console.log('response status', response.status());
//   console.log('response url', response.url());
//   expect(response.url()).toContain('/shared-photo');
// });
