/**
 * @file Invitation Flow Test
 * @description Tests the end-to-end functionality of inviting a new user to TimeSafari
 * 
 * This test verifies:
 * 1. User can create a new invitation with:
 *    - Custom notes
 *    - Custom expiration date
 * 2. The invitation appears in the list after creation
 * 3. A new user can accept the invitation and become connected
 * 
 * Test Flow:
 * 1. Imports User 0 (test account)
 * 2. Creates an invitation with:
 *    - Random neighbor identifier
 *    - 14 day expiration
 *    - Custom notes
 * 3. Verifies the invite appears in the list
 * 4. Creates a new user with Ethr DID
 * 5. Accepts the invitation as the new user
 * 6. Verifies the connection is established
 * 
 * Related Files:
 * - Frontend invite handling: src/libs/endorserServer.ts
 * - JWT creation: sw_scripts/safari-notifications.js
 * 
 * @see Documentation on invitation flows in usage-guide.md
 * @requires @playwright/test
 * @requires ./testUtils - For user management utilities
 */
import { test, expect } from '@playwright/test';
import { deleteContact, generateNewEthrUser, generateRandomString, importUser, switchToUser } from './testUtils';

test('Check User 0 can invite someone', async ({ page }) => {
  await importUser(page, '00');
  await page.goto('./invite-one');
  await page.locator('button > svg.fa-plus').click();
  const neighborNum = await generateRandomString(5);
  await page.getByPlaceholder('Notes', { exact: true }).fill(`Neighbor ${neighborNum}`);
  // get the expiration date input and set to 14 days from now
  const expirationDate = new Date(Date.now() + 14 * 24 * 60 * 60 * 1000);
  await page.locator('input[type="date"]').fill(expirationDate.toISOString().split('T')[0]);
  await page.locator('button:has-text("Save")').click();
  await expect(page.locator('div[role="alert"] button:has-text("Yes")')).toBeHidden();

  // check that the invite is in the list
  const newInviteLine = page.locator(`td:has-text("Neighbor ${neighborNum}")`);
  await expect(newInviteLine).toBeVisible();
  // retrieve the link from the title
  const inviteLink = await newInviteLine.getAttribute('data-testId');
  expect(inviteLink).not.toBeNull();

  // become the new user and accept the invite
  const newDid = await generateNewEthrUser(page);
  await switchToUser(page, newDid);
  await page.goto(inviteLink as string);
  await page.getByPlaceholder('Name', { exact: true }).fill(`My pal User #0`);
  await page.locator('button:has-text("Save")').click();
  await expect(page.locator('button:has-text("Save")')).toBeHidden();
  await expect(page.locator(`li:has-text("My pal User #0")`)).toBeVisible();
});
