/**
 * Catalog routes — marketing-catalogs-campaigns (wave-9 leaf 3).
 * Mounted at /api/marketing/catalog (behind authMiddleware in router.ts).
 *
 * GET    /items              list catalog items (with optional ?q= search and ?category= filter)
 * POST   /items              create catalog item
 * PATCH  /items/:id          update catalog item
 * DELETE /items/:id          delete catalog item
 * GET    /categories         list distinct categories
 */
import { Hono } from 'hono'
import type { AppEnv } from '../../types'
import { requirePermission } from '../../middleware/guards'
import {
  listCatalogItems,
  searchCatalogItems,
  createCatalogItem,
  updateCatalogItem,
  deleteCatalogItem,
  listCatalogCategories,
  createCatalogItemSchema,
  updateCatalogItemSchema,
} from '@zync/db/queries'

export const catalogRoute = new Hono<AppEnv>()

// GET /api/marketing/catalog/items
catalogRoute.get('/items', requirePermission('marketing:read'), async (c) => {
  const session = c.get('session')
  if (!session || session.type !== 'user' || !session.tid) return c.json({ error: 'Unauthorized' }, 401)
  const db = c.get('db')

  const q = c.req.query('q')
  const category = c.req.query('category')
  const activeOnly = c.req.query('active') !== 'false'

  let items
  if (q && q.trim()) {
    items = await searchCatalogItems(db, session.tid, q.trim())
  } else {
    items = await listCatalogItems(db, session.tid, { category: category ?? undefined, activeOnly })
  }

  return c.json({ items })
})

// POST /api/marketing/catalog/items
catalogRoute.post('/items', requirePermission('marketing:write'), async (c) => {
  const session = c.get('session')
  if (!session || session.type !== 'user' || !session.tid) return c.json({ error: 'Unauthorized' }, 401)
  const db = c.get('db')

  const body = await c.req.json().catch(() => null)
  const parsed = createCatalogItemSchema.safeParse(body)
  if (!parsed.success) return c.json({ error: 'Validation failed', issues: parsed.error.issues }, 400)

  const item = await createCatalogItem(db, session.tid, parsed.data)
  return c.json({ item }, 201)
})

// PATCH /api/marketing/catalog/items/:id
catalogRoute.patch('/items/:id', requirePermission('marketing:write'), async (c) => {
  const session = c.get('session')
  if (!session || session.type !== 'user' || !session.tid) return c.json({ error: 'Unauthorized' }, 401)
  const db = c.get('db')
  const { id } = c.req.param()

  const body = await c.req.json().catch(() => null)
  const parsed = updateCatalogItemSchema.safeParse(body)
  if (!parsed.success) return c.json({ error: 'Validation failed', issues: parsed.error.issues }, 400)

  try {
    const item = await updateCatalogItem(db, session.tid, id, parsed.data)
    return c.json({ item })
  } catch {
    return c.json({ error: 'Catalog item not found' }, 404)
  }
})

// DELETE /api/marketing/catalog/items/:id
catalogRoute.delete('/items/:id', requirePermission('marketing:write'), async (c) => {
  const session = c.get('session')
  if (!session || session.type !== 'user' || !session.tid) return c.json({ error: 'Unauthorized' }, 401)
  const db = c.get('db')
  const { id } = c.req.param()

  await deleteCatalogItem(db, session.tid, id)
  return c.json({ ok: true })
})

// GET /api/marketing/catalog/categories
catalogRoute.get('/categories', requirePermission('marketing:read'), async (c) => {
  const session = c.get('session')
  if (!session || session.type !== 'user' || !session.tid) return c.json({ error: 'Unauthorized' }, 401)
  const db = c.get('db')

  const categories = await listCatalogCategories(db, session.tid)
  return c.json({ categories })
})
