/**
 * Sprint 7 item 5 — визуально подтверждаем EmptyState на свежей организации.
 * Без seed-demo, просто заходим в /catalog/products и видим «Здесь пока пусто».
 */
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 = `empty-shot-${TS}@food-market.local`
const PASS = 'EmptyShot12345!'

async function ensureSession() {
  const api = makeClient()
  const r = await api.post('/api/auth/signup', {
    email: EMAIL, password: PASS,
    organizationName: `EmptyShot ${TS}`, phone: '+77011190001', plan: 'start',
  })
  if (r.status !== 200) 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 ${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 })

  await page.goto(`${BASE}/catalog/products`, { waitUntil: 'domcontentloaded' })
  await page.waitForLoadState('networkidle')
  // Жде EmptyState — он содержит текст «Здесь пока пусто»
  await page.waitForSelector('text=Здесь пока пусто', { timeout: 8000 })
  await page.screenshot({ path: `reports/empty-state-products-${TS}.png` })
  console.log(`[shot] products empty → reports/empty-state-products-${TS}.png`)

  // Также проверим SuppliesPage
  await page.goto(`${BASE}/purchases/supplies`, { waitUntil: 'domcontentloaded' })
  await page.waitForLoadState('networkidle')
  await page.waitForSelector('text=Приёмок пока нет', { timeout: 8000 })
  await page.screenshot({ path: `reports/empty-state-supplies-${TS}.png` })
  console.log(`[shot] supplies empty → reports/empty-state-supplies-${TS}.png`)

  await browser.close()
}

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