/**
 * AR Aging bulk statement send route — ar-aging-report (wave-12).
 *
 * POST /api/reports/ar-aging/statements
 *   Auth: authMiddleware + requirePermission('invoices:read') + admin role
 *   Body: ArAgingStatementsRequest
 *   200 -> ArAgingStatementsResponse { sent: number }
 *   400 -> empty customer_ids / invalid as_of
 *   403 -> non-admin
 */
import { Hono } from 'hono'
import { z } from 'zod'
import type { AppEnv } from '../../types'
import { isOwnerOrAdminRole } from '../../lib/system-roles'
import { authMiddleware } from '../../middleware/auth'
import { requirePermission } from '../../middleware/guards'
import { sendCustomerStatement } from '../../lib/ar-aging-statement'

const arAgingStatementsRoutes = new Hono<AppEnv>()

arAgingStatementsRoutes.use('*', authMiddleware)
arAgingStatementsRoutes.use('*', requirePermission('invoices:read'))

// ── Body schema ────────────────────────────────────────────────────────────────

const arAgingStatementsSchema = z.object({
  customer_ids: z.array(z.string().uuid()).min(1),
  subject: z.string().max(200).optional(),
  message: z.string().max(2000).optional(),
  as_of: z.string().date(),
})

// ── POST /ar-aging/statements ─────────────────────────────────────────────────

arAgingStatementsRoutes.post('/statements', async (c) => {
  const session = c.get('session')
  if (!session || session.type !== 'user' || !session.tid) {
    return c.json({ error: 'No tenant context' }, 403)
  }

  // Require admin role
  if (!isOwnerOrAdminRole(session.role)) {
    return c.json({ error: 'Admin role required to send statements' }, 403)
  }

  const tenantId = session.tid
  const db = c.get('db')
  const env = c.env

  let parsed: ReturnType<typeof arAgingStatementsSchema.safeParse>
  try {
    parsed = arAgingStatementsSchema.safeParse(await c.req.json())
  } catch {
    return c.json({ error: 'Invalid JSON body' }, 400)
  }
  if (!parsed.success) {
    return c.json({ error: 'Invalid request body', details: parsed.error.flatten() }, 400)
  }

  const { customer_ids, subject, message, as_of } = parsed.data

  // Resolve tenant default currency for statements
  // (customers may have different currencies; use ILS as the default)
  // A more complete implementation would look up tenant.defaultCurrency
  const currency = 'ILS'

  let sent = 0
  for (const customerId of customer_ids) {
    try {
      const result = await sendCustomerStatement(
        db,
        { tenantId, customerId, asOf: as_of, currency, subject, message },
        env,
      )
      if (result.sent) sent++
    } catch {
      // Log and continue; don't fail the whole batch for one customer
    }
  }

  return c.json({ sent })
})

export { arAgingStatementsRoutes }
