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

test('Services: full CRUD lifecycle', async ({ page }) => {
  const uid = Date.now().toString(36);
  const serviceTitle = `E2E Service ${uid}`;
  const updatedTitle = `${serviceTitle} Updated`;

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

  await page.locator('#title').fill(serviceTitle);
  await page.locator('#short-description').fill('Short description for E2E test service.');
  await page.locator('#full-description').fill('Full description for E2E test service with more details.');

  await page.locator('input[placeholder="Add a feature point..."]').fill('E2E Feature One');
  await page.getByRole('button', { name: 'Add' }).click();

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

  // Creation redirects to /services/:id (edit page)
  await expect(page.locator('h1')).toContainText('Edit Service', { timeout: 15_000 });

  // --- VERIFY IN LIST ---
  await page.goto('/services');
  await expect(page.getByText(serviceTitle)).toBeVisible({ timeout: 10_000 });

  // --- EDIT ---
  const row = page.locator('tr', { has: page.getByText(serviceTitle, { exact: false }) });
  const actionsCell = row.locator('td').last();
  await actionsCell.locator('button').first().click();

  await expect(page.locator('h1')).toContainText('Edit Service', { timeout: 10_000 });

  const titleInput = page.locator('#title');
  await titleInput.clear();
  await titleInput.fill(updatedTitle);

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

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

  // --- DELETE ---
  const updatedRow = page.locator('tr', { has: page.getByText(updatedTitle, { exact: false }) });
  const updatedActionsCell = updatedRow.locator('td').last();
  await updatedActionsCell.locator('button').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(updatedTitle)).toBeHidden({ timeout: 10_000 });
});
