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

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

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

  await page.locator('#title').fill(postTitle);

  const editor = page.locator('.ProseMirror');
  await editor.click();
  await editor.fill('This is E2E test content for the post.');

  await page.locator('#category').fill('E2E Testing');

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

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

  // --- VERIFY IN LIST ---
  await page.goto('/posts');
  await expect(page.getByRole('link', { name: postTitle })).toBeVisible({ timeout: 10_000 });

  // --- EDIT ---
  // Each row has two links: title link and pencil icon link; use the title link
  await page.getByRole('link', { name: postTitle }).click();
  await expect(page.locator('h1')).toContainText('Edit Post', { 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 TITLE ---
  await page.goto('/posts');
  await expect(page.getByText(updatedTitle)).toBeVisible({ timeout: 10_000 });

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

  await expect(page.getByText('Delete confirmation')).toBeVisible();
  // Target the modal's danger button specifically
  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 });
});
