/**
 * bituach-leumi.ts — Bituach Leumi report aggregation service.
 *
 * Orchestrates DB queries, KV rate loading, and NII estimation.
 *
 * Spec: 2026-06-01-bituach-leumi (spec 175, wave-15)
 */
import type { Db } from '@zync/db/queries'
import {
  getNiiReportAggregates,
  listNiiAdvances,
} from '@zync/db/queries'
import { estimateNIIContributions } from '../lib/nii-estimate'
import type { BituachLeumiReport, NIIRates } from '@zync/types'

/**
 * Build the full Bituach Leumi annual report.
 *
 * @param db              - Drizzle DB instance
 * @param tenantId        - Tenant ID
 * @param userId          - User ID (for advance payment lookup)
 * @param year            - Report year
 * @param depreciationDeduction - Manual depreciation deduction (default 0)
 * @param rates           - NII rates loaded from KV
 */
export async function getBituachLeumiReport(
  db: Db,
  tenantId: string,
  userId: string,
  year: number,
  depreciationDeduction: number,
  rates: NIIRates,
): Promise<BituachLeumiReport> {
  // Fetch aggregates and advances in parallel
  const [aggregates, advances] = await Promise.all([
    getNiiReportAggregates(db, tenantId, year),
    listNiiAdvances(db, tenantId, userId, year),
  ])

  const gross        = parseFloat(aggregates.grossRevenueNetVat)
  const expenses     = parseFloat(aggregates.deductibleExpenses)
  const payouts      = parseFloat(aggregates.contractorPayouts)
  const depreciation = Math.max(0, depreciationDeduction)

  const netIncome = gross - expenses - payouts - depreciation
  const monthlyAverage = netIncome / 12

  const niiContributions = estimateNIIContributions(netIncome, rates)

  const advancesTotal = advances.reduce((sum, a) => sum + a.amount, 0)
  const byMonth = advances.map((a) => ({ month: a.month, amount: a.amount }))

  return {
    year,
    gross_revenue_net_vat: gross.toFixed(2),
    deductible_expenses:   expenses.toFixed(2),
    contractor_payouts:    payouts.toFixed(2),
    depreciation_deduction: depreciation.toFixed(2),
    net_income:            netIncome.toFixed(2),
    monthly_average:       monthlyAverage.toFixed(2),
    nii_contributions:     niiContributions,
    advances_paid: {
      total: advancesTotal,
      by_month: byMonth,
    },
  }
}
