/**
 * Campaigns routes — marketing-catalogs-campaigns (wave-9 leaf 3).
 * Mounted at /api/marketing/campaigns (behind authMiddleware in router.ts).
 *
 * GET    /          list campaigns (optional ?status= filter)
 * POST   /          create campaign
 * PATCH  /:id       update campaign
 * POST   /:id/activate  activate campaign (sets status=active)
 */
import { Hono } from 'hono'
import type { AppEnv } from '../../types'
import { requirePermission } from '../../middleware/guards'
import {
  listCampaigns,
  createCampaign,
  updateCampaign,
  activateCampaign,
  createCampaignSchema,
  updateCampaignSchema,
} from '@zync/db/queries'

export const campaignsRoute = new Hono<AppEnv>()

// GET /api/marketing/campaigns
campaignsRoute.get('/', 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 status = c.req.query('status')
  const campaigns = await listCampaigns(db, session.tid, { status: status ?? undefined })
  return c.json({ campaigns })
})

// POST /api/marketing/campaigns
campaignsRoute.post('/', 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 = createCampaignSchema.safeParse(body)
  if (!parsed.success) return c.json({ error: 'Validation failed', issues: parsed.error.issues }, 400)

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

// PATCH /api/marketing/campaigns/:id
campaignsRoute.patch('/: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 = updateCampaignSchema.safeParse(body)
  if (!parsed.success) return c.json({ error: 'Validation failed', issues: parsed.error.issues }, 400)

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

// POST /api/marketing/campaigns/:id/activate
campaignsRoute.post('/:id/activate', 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()

  try {
    const campaign = await activateCampaign(db, session.tid, id)
    return c.json({ campaign })
  } catch {
    return c.json({ error: 'Campaign not found' }, 404)
  }
})
