/**
 * AR Aging export routes — ar-aging-report (wave-12).
 *
 * Mounted at /api/reports (declared in index.ts router).
 *
 * GET /api/reports/ar-aging/export.csv   -> text/csv  (Business+ only)
 * GET /api/reports/ar-aging/export.pdf   -> application/pdf OR text/html fallback (Business+ only)
 *
 * Both: authMiddleware + requirePermission('invoices:read') + requireTier('business')
 */
import { Hono } from 'hono'
import { z } from 'zod'
import { TenantTier } from '@zync/types'
import type { AppEnv } from '../../types'
import { authMiddleware } from '../../middleware/auth'
import { requirePermission, requireTier } from '../../middleware/guards'
import { buildArAgingReport } from '@zync/db/queries'
import { buildArAgingCsv } from '../../lib/ar-aging-csv'
import { buildArAgingHtml } from '../../lib/ar-aging-pdf'

const arAgingExportRoutes = new Hono<AppEnv>()

arAgingExportRoutes.use('*', authMiddleware)
arAgingExportRoutes.use('*', requirePermission('invoices:read'))
arAgingExportRoutes.use('*', requireTier(TenantTier.BUSINESS))

// ── Query schema ───────────────────────────────────────────────────────────────

const arAgingQuerySchema = z.object({
  as_of: z.string().date().optional(),
  currency: z.string().length(3).toUpperCase().optional(),
})

// ── GET /ar-aging/export.csv ───────────────────────────────────────────────────

arAgingExportRoutes.get('/export.csv', async (c) => {
  const session = c.get('session')
  if (!session || session.type !== 'user' || !session.tid) {
    return c.json({ error: 'No tenant context' }, 403)
  }
  const tenantId = session.tid
  const db = c.get('db')

  const parsed = arAgingQuerySchema.safeParse(c.req.query())
  if (!parsed.success) {
    return c.json({ error: 'Invalid query params', details: parsed.error.flatten() }, 400)
  }

  const { as_of, currency } = parsed.data
  const report = await buildArAgingReport(db, tenantId, { asOf: as_of, currency })

  const csv = buildArAgingCsv(report)
  const filename = `ar-aging-${report.asOf}.csv`

  return new Response(csv, {
    headers: {
      'Content-Type': 'text/csv; charset=utf-8',
      'Content-Disposition': `attachment; filename="${filename}"`,
    },
  })
})

// ── GET /ar-aging/export.pdf ───────────────────────────────────────────────────

arAgingExportRoutes.get('/export.pdf', async (c) => {
  const session = c.get('session')
  if (!session || session.type !== 'user' || !session.tid) {
    return c.json({ error: 'No tenant context' }, 403)
  }
  const tenantId = session.tid
  const db = c.get('db')

  const parsed = arAgingQuerySchema.safeParse(c.req.query())
  if (!parsed.success) {
    return c.json({ error: 'Invalid query params', details: parsed.error.flatten() }, 400)
  }

  const { as_of, currency } = parsed.data
  const report = await buildArAgingReport(db, tenantId, { asOf: as_of, currency })

  // Detect tenant locale from session to choose RTL/Hebrew
  // SessionPayload carries tenant info; default to 'he' (IL-first)
  const locale: 'he' | 'en' = 'he'

  const html = buildArAgingHtml(report, locale)
  const filename = `ar-aging-${report.asOf}.html`

  // HTML-to-PDF Worker pattern:
  // In a full implementation, the HTML would be posted to a PDF-render Worker.
  // That Worker binding is not yet provisioned in this wave (spec defers PDF Worker
  // provisioning to a future infrastructure wave). We return the HTML with a
  // print-fallback header so the client can invoke window.print().
  return new Response(html, {
    headers: {
      'Content-Type': 'text/html; charset=utf-8',
      'Content-Disposition': `attachment; filename="${filename}"`,
      'Content-Security-Policy': "sandbox; default-src 'none'; style-src 'unsafe-inline'",
      'X-Print-Fallback': 'true',
    },
  })
})

export { arAgingExportRoutes }
