import { describe, expect, it, vi } from 'vitest'
import { Hono } from 'hono'
import type { AppEnv } from '../src/types'

const requirePermissionMock = vi.fn(() => async (_c: unknown, next: () => Promise<void>) => next())
const getUnifiedWithholdingReportMock = vi.fn(async () => ({
  year: 2026,
  total_gross: '2800.00',
  total_withheld: '280.00',
  payees: [
    {
      payee_kind: 'contractor',
      payee_id: 'ctr-1',
      name: 'Dana',
      tax_id: '123',
      gross_paid: '1000.00',
      withholding_rate: '0.1000',
      withheld_amount: '100.00',
      certificate_number: '456/2026',
      certificate_expiry: '2026-12-31',
    },
    {
      payee_kind: 'vendor',
      payee_id: 'vendor-1',
      name: 'AWS',
      tax_id: '514000000',
      gross_paid: '1800.00',
      withholding_rate: '0.1000',
      withheld_amount: '180.00',
      certificate_number: null,
      certificate_expiry: null,
    },
  ],
}))

vi.mock('../src/middleware/auth', () => ({
  authMiddleware: async (c: { set: (key: string, value: unknown) => void }, next: () => Promise<void>) => {
    c.set('session', { type: 'user', tid: 'tenant-1', sub: 'user-1' })
    c.set('db', {})
    await next()
  },
}))

vi.mock('../src/middleware/guards', () => ({
  requirePermission: (...args: unknown[]) => requirePermissionMock(...args),
}))

vi.mock('@zync/db/queries', () => ({
  getUnifiedWithholdingReport: (...args: unknown[]) => getUnifiedWithholdingReportMock(...args),
  withholdingReportSchema: {
    safeParse: (input: { year?: string }) => ({
      success: true as const,
      data: { year: Number(input.year) },
    }),
  },
}))

describe('reports withholding routes', () => {
  it('serves the unified 856 report behind reports:read', async () => {
    const { withholdingReportRoutes } = await import('../src/routes/reports/withholding')
    const app = new Hono<AppEnv>()
    app.route('/api/reports', withholdingReportRoutes)

    const res = await app.request('/api/reports/withholding?year=2026')
    expect(res.status).toBe(200)
    expect(requirePermissionMock).toHaveBeenCalledWith('reports:read')

    const body = await res.json()
    expect(body.payees).toHaveLength(2)
    expect(body.payees[0].payee_kind).toBe('contractor')
    expect(body.payees[1].payee_kind).toBe('vendor')
  })
})
