import { Hono } from 'hono'
import type { AppEnv } from '../../types'
import { authMiddleware } from '../../middleware/auth'
import { requirePermission } from '../../middleware/guards'
import { getUnifiedWithholdingReport, withholdingReportSchema } from '@zync/db/queries'
import { buildForm857Xlsx, buildWithholdingReportXlsx } from '../../lib/contractor-payout-exports'

export const withholdingReportRoutes = new Hono<AppEnv>()

withholdingReportRoutes.use('*', authMiddleware)
withholdingReportRoutes.use('*', requirePermission('reports:read'))

withholdingReportRoutes.get('/withholding', async (c) => {
  const session = c.get('session')
  if (!session || session.type !== 'user' || !session.tid) {
    return c.json({ error: 'Unauthorized' }, 401)
  }

  const query = withholdingReportSchema.safeParse(
    Object.fromEntries(new URL(c.req.url).searchParams),
  )
  if (!query.success) {
    return c.json({ error: 'Invalid query', issues: query.error.issues }, 400)
  }

  const report = await getUnifiedWithholdingReport(c.get('db'), session.tid, query.data.year)
  return c.json(report, 200)
})

withholdingReportRoutes.get('/withholding/xlsx', async (c) => {
  const session = c.get('session')
  if (!session || session.type !== 'user' || !session.tid) {
    return c.json({ error: 'Unauthorized' }, 401)
  }

  const query = withholdingReportSchema.safeParse(
    Object.fromEntries(new URL(c.req.url).searchParams),
  )
  if (!query.success) {
    return c.json({ error: 'Invalid query', issues: query.error.issues }, 400)
  }

  const report = await getUnifiedWithholdingReport(c.get('db'), session.tid, query.data.year)
  const bytes = await buildWithholdingReportXlsx(report)
  return new Response(bytes, {
    status: 200,
    headers: {
      'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'Content-Disposition': `attachment; filename="withholding-report-${query.data.year}.xlsx"`,
      'Content-Length': String(bytes.byteLength),
      'X-Content-Type-Options': 'nosniff',
    },
  })
})

withholdingReportRoutes.get('/withholding/:payeeKind/:payeeId/form-857', async (c) => {
  const session = c.get('session')
  if (!session || session.type !== 'user' || !session.tid) {
    return c.json({ error: 'Unauthorized' }, 401)
  }

  const query = withholdingReportSchema.safeParse(
    Object.fromEntries(new URL(c.req.url).searchParams),
  )
  if (!query.success) {
    return c.json({ error: 'Invalid query', issues: query.error.issues }, 400)
  }

  const report = await getUnifiedWithholdingReport(c.get('db'), session.tid, query.data.year)
  try {
    const bytes = await buildForm857Xlsx(report, c.req.param('payeeId'))
    return new Response(bytes, {
      status: 200,
      headers: {
        'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'Content-Disposition': `attachment; filename="form-857-${query.data.year}-${c.req.param('payeeKind')}-${c.req.param('payeeId')}.xlsx"`,
        'Content-Length': String(bytes.byteLength),
        'X-Content-Type-Options': 'nosniff',
      },
    })
  } catch {
    return c.json({ error: 'Not found' }, 404)
  }
})
