/**
 * Sprint 7 item 3 — визуальная проверка toast'a на стейдже.
 * Логинимся → провоцируем 404 (несуществующий товар) → ждём toast → скриншот.
 */
import { chromium } from 'playwright'
import { makeClient, login } from '../lib/api.js'

const BASE = process.env.E2E_ADMIN_URL ?? 'https://test.admin.food-market.kz'
const TS = Date.now()
const EMAIL = process.env.E2E_EMAIL ?? `toast-shot-${TS}@food-market.local`
const PASS = process.env.E2E_PASSWORD ?? 'ToastShot12345!'

async function ensureSession() {
  const api = makeClient()
  const r = await api.post('/api/auth/signup', {
    email: EMAIL, password: PASS,
    organizationName: `ToastShot ${TS}`, phone: '+77011190001', plan: 'start',
  })
  if (r.status !== 200 && r.status !== 409) throw new Error(`signup ${r.status}: ${JSON.stringify(r.data)}`)
  return login(EMAIL, PASS)
}

async function main() {
  const sess = await ensureSession()
  console.log(`[shot] session ok ${sess.email}`)

  const browser = await chromium.launch({ headless: true })
  const ctx = await browser.newContext({ ignoreHTTPSErrors: true, viewport: { width: 1280, height: 800 } })
  const page = await ctx.newPage()
  await page.goto(`${BASE}/`)
  await page.evaluate(({ token }) => localStorage.setItem('fm.access_token', token), { token: sess.accessToken })

  // Идём на несуществующий продукт — должна сработать 404 с тостом.
  await page.goto(`${BASE}/catalog/products/00000000-0000-0000-0000-000000000000`, { waitUntil: 'domcontentloaded' })
  await page.waitForLoadState('networkidle')
  // Ждём наш toast (role=alert + Не найдено)
  await page.waitForSelector('[role="alert"]', { timeout: 10000 })
  await page.waitForTimeout(400)
  await page.screenshot({ path: `reports/toast-error-${TS}.png`, fullPage: false })
  console.log(`[shot] saved → reports/toast-error-${TS}.png`)

  await browser.close()
}

main().catch(err => { console.error(err); process.exit(1) })
