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

test('Users: full CRUD lifecycle', async ({ page }) => {
  const uid = Date.now().toString(36);
  const userName = `E2E User ${uid}`;
  const userEmail = `e2e-${uid}@test.local`;
  const updatedName = `${userName} Updated`;

  // --- CREATE ---
  await page.goto('/users/new');
  await expect(page.locator('h1')).toContainText('New User');

  await page.locator('#full-name').fill(userName);
  await page.locator('#email-address').fill(userEmail);
  await page.locator('#password').fill('Test123456');
  await page.locator('#role').selectOption('editor');

  await page.getByRole('button', { name: 'Create user' }).click();

  // Creation redirects to /users list
  await expect(page.locator('h1')).toContainText('Users', { timeout: 15_000 });
  await expect(page.getByText(userName)).toBeVisible({ timeout: 10_000 });

  // --- EDIT ---
  const row = page.locator('tr', { has: page.getByText(userName, { exact: false }) });
  await row.locator('a[href*="/users/"]').click();
  await expect(page.locator('h1')).toContainText('Edit User', { timeout: 10_000 });

  const nameInput = page.locator('#full-name');
  await nameInput.clear();
  await nameInput.fill(updatedName);

  await page.getByRole('button', { name: 'Save changes' }).click();
  await expect(page.getByText(/updated|saved/i)).toBeVisible({ timeout: 10_000 });

  // --- VERIFY UPDATED ---
  await page.goto('/users');
  await expect(page.getByText(updatedName)).toBeVisible({ timeout: 10_000 });

  // --- DELETE ---
  const updatedRow = page.locator('tr', { has: page.getByText(updatedName, { exact: false }) });
  await updatedRow.locator('button').filter({ has: page.locator('svg') }).last().click();

  await expect(page.getByText('Delete confirmation')).toBeVisible();
  await page.locator('.fixed button', { hasText: 'Delete' }).last().click();

  await expect(page.getByText(/deleted/i)).toBeVisible({ timeout: 10_000 });
  await expect(page.getByText(updatedName)).toBeHidden({ timeout: 10_000 });
});
