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

// Ops-gated: happy-path needs live dev server + seeded Neon branch (same harness as e2e/admin.spec.ts).
// The missing-slug case is a public-route floor that needs no seed.

const ADMIN_EMAIL = 'admin@e2e.test';
const ADMIN_PASSWORD = 'e2e-admin-pw-9f3a2b1c';
const ORIGIN = 'http://localhost:4331';

async function signIn(page: import('@playwright/test').Page) {
  await page.goto('/admin/login');
  await page.getByLabel('Email').fill(ADMIN_EMAIL);
  await page.getByLabel('Password').fill(ADMIN_PASSWORD);
  await page.getByRole('button', { name: 'Sign in' }).click();
  await page.waitForURL('**/admin');
}

async function createViaApi(
  page: import('@playwright/test').Page,
  input: { slug: string; title: string; body: string; type?: string; visibility?: string },
): Promise<{ id: string; slug: string }> {
  const res = await page.request.post('/api/admin/content', {
    headers: { origin: ORIGIN, 'content-type': 'application/json' },
    data: { type: 'post', ...input },
  });
  expect(res.ok(), `create failed: ${res.status()} ${await res.text()}`).toBeTruthy();
  return (await res.json()) as { id: string; slug: string };
}

async function publishViaApi(page: import('@playwright/test').Page, id: string): Promise<void> {
  const res = await page.request.post('/api/admin/publish', {
    headers: { origin: ORIGIN, 'content-type': 'application/json' },
    data: { id },
  });
  expect(res.ok(), `publish failed: ${res.status()} ${await res.text()}`).toBeTruthy();
}

test('GET /post/<missing> returns 404 not 500', async ({ request }) => {
  const res = await request.get(`/post/does-not-exist-${Date.now()}`);
  expect(res.status(), await res.text()).toBe(404);
});

test('GET /post/<published-slug> returns 200 with title and body', async ({ page }) => {
  const stamp = Date.now();
  const slug = `e2e-pub-${stamp}`;
  const title = `Published post ${stamp}`;
  const bodyText = `Happy path body ${stamp}`;

  await signIn(page);
  const { id } = await createViaApi(page, {
    slug,
    title,
    body: `<p>${bodyText}</p>`,
    visibility: 'public',
  });
  await publishViaApi(page, id);

  const res = await page.request.get(`/post/${slug}`);
  expect(res.status(), await res.text()).toBe(200);
  const html = await res.text();
  expect(html).toContain(title);
  expect(html).toContain(bodyText);
});
