export { tenantQuery } from './tenant-query'
export type { TenantQueryResult } from './tenant-query'
export {
  InvalidTenantReferenceError,
  invalidTenantReferenceBody,
  assertTenantOwnsOrThrow,
  assertTenantOwnsProject,
  assertTenantOwnsCustomer,
  assertTenantOwnsLead,
  assertTenantOwnsInvoice,
  assertTenantOwnsKbSpace,
  assertTenantOwnsKbArticle,
  assertTenantOwnsTask,
  assertTenantOwnsTaskStatus,
  assertTenantOwnsTicketCategory,
  assertActiveTenantAssignee,
  assertTenantOwnsContact,
} from './tenant-guards'
export { systemQuery } from './system-query'
export type { SystemQueryResult } from './system-query'

// Re-export the client from the queries subpath so route files (which may only
// import from a path containing "queries", per no-raw-drizzle-from-routes) can
// construct a Db without importing the package root.
export { createDb } from '../client'
export type { Db, DbTx } from '../client'

// foundation-auth-rbac query helpers
export { incrementCounter, checkCounterLimit, QuotaExceededError } from './usage'
export { getQuotaLimit } from './quota-config'
export { seedPermissions, seedSystemRoles } from './seed-rbac'

// foundation-auth-rbac auth read helpers
export {
  findUserByEmail,
  findUserById,
  findAdminByEmail,
  findAdminById,
  findAdminWithPermissions,
  getTenantById,
  getMembership,
  getPrimaryMembership,
  getMembershipView,
  getPermissionsForRole,
  getRoleByName,
  getRoleById,
  getMeView,
  getActiveRefreshTokenByHash,
  countActiveRefreshTokens,
  countActiveMembers,
  getInvitationByHash,
  getInvitationPublicMetadataByHash,
} from './auth-reads'

// foundation-auth-rbac audited write helpers
export {
  createPendingUser,
  completeEmailVerification,
  markUserEmailVerified,
  insertRefreshToken,
  rotateRefreshToken,
  revokeRefreshToken,
  resetUserPassword,
  createInvitation,
  createInvitationInTx,
  acceptInvitationExistingUser,
  freezeMembership,
  setAdminTotpSecret,
} from './auth-writes'
export type { VerifyEmailResult } from './auth-writes'
export {
  cleanupE2eRoleFixture,
  E2eFixtureConflictError,
  provisionE2eRoleFixture,
} from './e2e-role-fixtures'
export type { E2eRoleFixture, E2eRoleFixtureUser } from './e2e-role-fixtures'

// auth-2fa: extended primary membership query (includes tenant 2FA settings)
export { getPrimaryMembershipWithTenant } from './auth-reads'
// auth-2fa: magic-link / pending-2FA token helpers
export { insertMagicLinkToken, findPendingToken, consumeMagicLinkToken } from './magic-link-tokens'
// auth-2fa: backup code helpers
export { insertBackupCodes, consumeBackupCode, countUnusedBackupCodes, deleteUnusedBackupCodes } from './backup-codes'
// auth-2fa: trusted device helpers
export { findValidTrustedDevice, createTrustedDevice, listTrustedDevices, revokeTrustedDevice, revokeAllTrustedDevices, revokeAllTrustedDevicesForTenant } from './trusted-devices'
// auth-2fa: 2FA read helpers
export { getUser2FAStatus, getTenant2FASettings, getMember2FAStats, getActiveMemberIds } from './two-factor-reads'
export type { UserWith2FA, TenantWith2FA } from './two-factor-reads'
// auth-2fa: 2FA write helpers
export { enable2FA, disable2FA, updateTenant2FASettings } from './two-factor-writes'

// customers-module query helpers
export type { Address, Customer, CustomerContact, CustomerPortalUser, CustomerCommunication, CustomerStats, CustomerListPage, CustomerActorContext } from './customers'
export { OpenInvoicesError, listCustomers, getCustomerWithStats, createCustomer, updateCustomer, archiveCustomer, getContactById, listContacts, addContact, updateContact, removeContact, getPortalUserById, listPortalUsers, createPortalUser, setPortalUserStatus, listCommunications, appendCustomerCommunication } from './customers'
export { recordSystemCommunication } from './customer-communications-hooks'

// dark-light-theme query helpers
export { getUserTheme, setUserTheme, setUserShell } from './user-preferences'
export type { UiTheme, UiShell } from './user-preferences'
export {
  getShellLayout,
  getShellPreferences,
  setShellLayout,
  deleteShellLayout,
} from './shell-layout'
export type {
  ShellLayoutRecord,
  ShellPreferences,
  UiShell as ShellLayoutUiShell,
} from './shell-layout'

// module-management query helpers
export {
  seedTenantModules,
  getTenantModules,
  getEnabledModuleIds,
  setModuleStates,
  setModuleStateAdmin,
} from './tenant-modules'
export type { TenantModuleRow } from './tenant-modules'

// system-ai query helpers
export {
  getGlobalConfig,
  updateGlobalConfig,
  listModelPricing,
  getModelPricing,
  addModel,
  updateModelPricing,
  setModelActive,
  getTierQuotas,
  upsertTierQuota,
  getTenantSettings,
  upsertTenantSettings,
  insertUsageLog,
  listUsageLog,
  tenantUsageBreakdown,
  tokensByUseCase,
  costByTenant,
  errorRateByModel,
  costTrend,
  getCreditPurchases,
  insertCreditPurchase,
  deductPurchasedCredit,
  getUsageCounter,
  incrementCounterBy,
  getExtraSpendThisMonth,
} from './ai'
export type {
  ModelConfig,
  GlobalConfigResult,
  AITenantSettings,
  AIUsageLogInsert,
  UsageLogFilter,
  PageParams,
} from './ai'

// system-communications-notifications query helpers
export {
  upsertPushSubscription,
  deletePushSubscription,
  getPushSubscriptionsForUser,
  deletePushSubscriptionByEndpoint,
  countPushSubscriptionsForUser,
  insertNotification,
  getNotificationsForUser,
  markNotificationRead,
  markAllNotificationsRead,
  saveAdapterCredentialRow,
  loadAdapterCredentialRow,
  findSlackCredentialByTeamId,
} from './communications'
export { createNotification } from './notifications'
export { routeInboundMessage } from './inbound'
export type { TenantCommsConfig } from './inbound'
export {
  getUserEmailPrefs,
  getUserTelegramPrefs,
  getUserEmailAndLocale,
  getUserTelegramChatId,
} from './user-comms'

// system-i18n query helpers
export { getVatRate } from './vat'
export { loadCountryAdapter, getTenantCountryAdapter, UnsupportedCountryError } from './country'
export {
  getUserLocalePreference,
  setUserLocale,
  setTenantCountryCode,
  setTenantForceShell,
  getTenantAccountSettings,
  updateTenantAccountSettings,
  getSmtpSettings,
  updateSmtpSettings,
} from './preferences'
export type { TenantAccountSettings, SmtpSettings } from './preferences'

// app-shell query helpers
export type { TenantMembershipSummary, MemberPermissionRow } from './memberships'
export { getUserActiveMemberships, getMembersByPermission } from './memberships'

// admin-dashboard query helpers
export {
  getTaxRate,
  listTaxRates,
  addTaxRate,
  assertTaxRateMutable,
  listVatRatesForAdmin,
  TaxRateConflictError,
  TaxRateValidationError,
} from './tax'
export type { TaxRateListRow, VatRateAdminRow } from './tax'
export {
  ProductNameConflictError,
  serializeProduct,
  listProducts,
  listInventoryCountRows,
  getInventoryReports,
  getProduct,
  getProductInventoryHistory,
  createProduct,
  updateProduct,
  setProductStockItemId,
  setProductActive,
  deleteProduct,
  productInUse,
  listTrackedInvoiceStockItems,
} from './products'
export { getInventoryReport, summarizeInventoryReport } from './inventory'
export {
  getDefaultInventoryLocationId,
  postInventoryReceipt,
  reverseInventorySale,
} from './inventory-posting'
export type { InventoryReceiptInput } from './inventory-posting'

export {
  listTenantsAdmin,
  getTenantDetailAdmin,
  listTenantUsersAdmin,
  approvePendingMember,
  freezeTenantMember,
  unfreezeTenantMember,
  revokeUserRefreshTokensForTenant,
  revokePendingInvitation,
} from './admin-tenants'
export type { AdminTenantRow, AdminTenantDetail, AdminTenantUserRow } from './admin-tenants'

export {
  getPlatformStats,
  getRecentAdminActivity,
  getTenantAuditLog,
} from './admin-stats'
export type { PlatformStats, AdminAuditRow, TenantAuditLogParams } from './admin-stats'

export {
  listAdminRoles,
  getAdminRoleById,
  createAdminRole,
  updateAdminRole,
  deleteAdminRole,
  resolveAdminPermissions,
  AdminRoleSystemError,
  AdminRoleInUseError,
  AdminRoleNotFoundError,
} from './admin-roles'
export type { AdminRoleListRow, CreateAdminRoleInput, UpdateAdminRoleInput } from './admin-roles'

export {
  listTenantRolesAdmin,
  createTenantRole,
  updateTenantRolePermissions,
  deleteTenantRole,
} from './admin-tenant-roles'

export {
  writeAdminAuditLog,
} from './admin-audit'
export type { AdminAuditInput } from './admin-audit'

// ai-assistant query helpers
export { createAiChatSession, getAiChatSession, listAiChatSessions, deleteAiChatSession, touchAiChatSession, appendAiChatMessage, getAiChatMessages, lastAiChatMessages, lastTelegramAiMessages, lastWhatsAppAiMessages } from './ai-chat'
export type { AiChatSession, AiChatMessage } from './ai-chat'

// kb-module query helpers
export { kbTenantQuery, kbPortalQuery } from './kb'

// platform-jobs query helpers
export {
  claimJobIdempotencyKey,
  markJobIdempotencyKeyProcessed,
  releaseJobIdempotencyKey,
  listJobIdempotencyKeys,
  claimPendingPlatformJobs,
  markPlatformJobProcessed,
  requeuePlatformJob,
  listPlatformJobs,
} from './jobs'
export type { JobQueryDb, JobIdempotencyKeyRow, PlatformJobRow } from './jobs'

// kb-versioning query helpers
export {
  createArticleVersion,
  createArticleVersionWithRetry,
  listArticleVersions,
  getArticleVersion,
  restoreArticleVersion,
} from './kb-versions'
export type {
  CreateArticleVersionInput,
  ArticleVersionSnapshot,
  ArticleVersionListItem,
  ArticleVersionFull,
  RestoreVersionResult,
} from './kb-versions'

// projects-module query helpers
export { listProjects, getProjectById, getProjectWithStats, createProject, updateProject, archiveProject, listProjectMembers, addProjectMember, updateProjectMember, removeProjectMember, getProjectHours, listRetainerMonths, incrementRetainerHours, rollOverRetainerHours } from './projects'
export type { ProjectActorContext } from './projects'

// tenant-audit-log query helpers
export { logAuditEvent } from './audit'
export { listAuditLog, fetchAuditLogForExport, purgeAuditLogByRetention, encodeCursor, decodeCursor } from './audit-list'
export type { AuditLogListOptions, AuditLogExportOptions, AuditLogPage } from './audit-list'

// zync-subscription query helpers
export {
  getSubscriptionByTenantId,
  getExpiredTrials,
  createFreelancerSubscription,
  cancelSubscription,
  markSubscriptionCanceled,
  reactivateCanceledSubscription,
  activateSubscription,
  upsertAdminSubscription,
  downgradeToFreelancerDb,
  setGracePeriodStarted,
  updateSubscriptionTier,
  getSubscriptionByTenantSlug,
  getTenantIdBySlug,
  logAdminSubscriptionOverride,
} from './subscriptions'
export type { ZyncSubscriptionRow, NewZyncSubscription, AdminSubscriptionAuditInput } from './subscriptions'

// zync-subscription: usage counter helpers
export { getCounterValue, decrementCounter } from './usage'

// expenses-module query helpers
export {
  listExpenses,
  getExpense,
  getExpenseById,
  createExpense,
  updateExpense,
  softDeleteExpense,
  setExpenseStatus,
  serializeExpenseRow,
  serializeCorrectionRow,
  getExpenseSettings,
  updateExpenseSettings,
  expenseReport,
  expenseReportDetail,
  vatSummaryPcn874,
  vatSummaryPcn874Ui,
  vendorAnalysis,
  vendorAnalysisUi,
  listExpensesByIds,
  listNeedsReviewExpenseIds,
} from './expenses'
export type {
  ExpenseFilters,
  EditableExpenseFields,
  NewExpenseInput,
  ReportFilters,
  ExpenseReportRow,
  ExpenseReportsUiFilters,
  ExpenseReportDetail,
  ExpenseReportDetailRow,
  VatSummary,
  VatSummaryUi,
  VatSummaryUiLine,
  VendorAnalysisRow,
  VendorAnalysisUiRow,
  ExpenseActorContext,
} from './expenses'

// tasks-board-engine query helpers
export {
  listTasks,
  getTask,
  createTask,
  updateTask,
  deleteTask,
  bulkUpdateStatus,
  setTaskLabels,
  encodeCursor as encodeTaskCursor,
  decodeCursor as decodeTaskCursor,
} from './tasks'
export type { TaskObject as TaskQueryObject } from './tasks'
export {
  listStatuses,
  getTaskStatusById,
  createStatus,
  updateStatus,
  deleteStatus,
  reorderStatuses,
  taskSyncSettings,
  getTaskSyncSettings,
  upsertTaskSyncSettings,
} from './task-statuses'
export type { TaskSyncSettingsRow } from './task-statuses'

// system-status-page query helpers
export {
  serializeIncidentUpdate,
  serializeIncident,
  deriveServiceStatuses,
  deriveOverallStatus,
  getActiveIncidents,
  getIncidentHistory,
  createIncident,
  addIncidentUpdate,
  resolveIncident,
  addSubscriber,
  listSubscribers,
  getSubscriberByToken,
  removeSubscriber,
  IncidentNotFoundError,
  IncidentAlreadyResolvedError,
} from './status'

// notification-center query helpers
export { getNotificationsAll } from './notifications-all'
export type { NotificationsAllRow, NotificationsAllResult, NotificationsAllInput } from './notifications-all'

// notification-preferences query helpers (spec 97)
export { getNotificationPreferences, updateNotificationPreferences } from './notification-preferences'
export type { NotificationPreferences, NotificationEventPrefs } from './notification-preferences'

// settings-module: team members + invitations (wave-10 leaf 2)
export {
  listTeamMembers,
  listPendingInvites,
  getActiveMemberEmailsForTenant,
  updateMemberRole,
  updateUserHourlyCost,
  removeTenantMember,
  revokePendingInvite,
} from './team-members'
export type { TeamMemberRow, PendingInviteRow } from './team-members'

// calendar-module query helpers
export {
  listCalendarEvents,
  listTasksDueInRange,
  listProjectMilestonesDueInRange,
  getCalendarEvent,
  createCalendarEvent,
  updateCalendarEvent,
  deleteCalendarEvent,
  upsertExternalCalendarEvent,
  listCalendarConnections,
  getCalendarConnection,
  getCalendarConnectionById,
  listSyncEnabledConnections,
  upsertCalendarConnection,
  updateCalendarConnectionTokens,
  updateCalendarConnectionLastSynced,
  updateCalendarConnection,
  deleteCalendarConnection,
  listSchedulingConnections,
  getSchedulingConnection,
  getSchedulingConnectionById,
  upsertSchedulingConnection,
  deleteSchedulingConnection,
  getSchedulingConnectionByTenant,
  findCustomerByContactEmail,
  getTenantFirstMemberId,
} from './calendar'
export type {
  CalendarConnectionRow,
  SchedulingConnectionRow,
} from '../schema/calendar'

// recurring-tasks-templates query helpers
export {
  listRecurringTasks,
  getRecurringTask,
  createRecurringTask,
  updateRecurringTask,
  deleteRecurringTask,
  listActiveRecurringTasks,
  touchRecurringGenerated,
  generateTaskFromRecurring,
  listTaskTemplates,
  createTaskTemplate,
  deleteTaskTemplate,
} from './recurring-tasks'
export type { RecurringTaskRow } from '../schema/recurring-tasks'
// Request-validation schemas — re-exported through the queries barrel so route
// handlers reach them via the sanctioned @zync/db/queries entry point (the
// no-raw-drizzle-from-routes lint rule blocks any other @zync/db/* subpath).
export {
  createRecurringTaskSchema,
  updateRecurringTaskSchema,
  createTaskTemplateSchema,
} from '../validation/recurring-tasks'

// task-dependencies query helpers
export {
  getDependencies,
  getProjectEdges,
  getProjectIdsForTasks,
  insertDependency,
  deleteDependency,
  assertSameProject,
  wouldCreateCycle,
  computeCriticalPath,
  getCachedCriticalPath,
  getProjectRevision,
  bumpProjectRevision,
  getUnsatisfiedBlockers,
  DuplicateDependencyError,
  CrossProjectDependencyError,
} from './task-dependencies'
export type { InsertDependencyInput } from './task-dependencies'

// tasks-detail-communication query helpers
export { listTaskMessages, createTaskMessage, recordTaskSystemMessage, softDeleteTaskMessage, addMessageAttachment, getTaskMessageById, getMessageAttachment, deleteMessageAttachmentRow, insertDraftAttachment, reparentAttachments } from './task-messages'
export type { TaskMessageRow, TaskAttachmentRow } from './task-messages'
export { recordTaskAudit, listTaskAudit } from './task-audit'
export type { TaskAuditRow as DbTaskAuditRow } from './task-audit'

// time-management query helpers
export {
  getActiveEntry,
  startEntry,
  stopEntry,
  listEntries,
  logManualEntry,
  updateEntry,
  deleteEntry,
  getWeekSummary,
  findStaleRunningEntries,
  stopStaleEntry,
  serializeTimeEntry,
  serializeTimeEntryBase,
  getTenantRounding,
  getTimeTrackingSettings,
  updateTimeTrackingSettings,
  getTimeEntryById,
  insertTimerMagicLinkToken,
  findTimerMagicLinkByHash,
  consumeTimerMagicLink,
  getTaskProjectId,
  getTaskTitle,
  getUserByEmail,
  getActiveTenantMemberByEmail,
  getUserEmailById,
} from './time'
export type {
  ListEntriesFilter,
  TimeActorContext,
  TimeTrackingSettingsRow,
  UpdateTimeTrackingSettingsPatch,
} from './time'

// trial-expiry-conversion-ui query helpers
export { ackTrialExpiry, stampTrialWarningSent, getActiveTrials } from './trial-expiry'

// invoices-core query helpers (wave-6)
export { listInvoices, getInvoice, getInvoiceWithLines, createInvoice, createInvoiceInTx, updateInvoice, deleteDraftInvoice, sendInvoice, approveInvoice, rejectInvoice, issueTaxInvoiceTx, issueTaxInvoice, setInvoiceHtmlSnapshotUrl, recordPayment, createCreditNote, voidInvoiceTx, voidInvoice, autoIssueInvoice, getVatRateForDate, nextInvoiceNumber, renderInvoiceHtml, recalculateInvoiceTotals, ConflictError, NotFoundError } from './invoices'
export {
  DEFAULT_SEQUENCE_PREFIXES,
  syncInvoiceSequencePrefixes,
  resolveInvoiceSequencePrefixes,
} from './invoice-sequences'
export type { Invoice, InvoiceLine, InvoiceWithLines, InvoiceListPage, InvoiceStatus, InvoiceActorContext } from './invoices'
export { createInvoiceSchema, updateInvoiceSchema, rejectInvoiceSchema, voidInvoiceSchema, recordPaymentSchema, listInvoicesSchema, autoIssueSchema, invoiceLineSchema } from './invoices'

// invoice-credit-notes (wave-12) query helpers
export { createCreditNoteDraft, issueCreditNote, listCreditNotesForParent, assertDeletableCreditNote, CreditNoteError, creditNoteLineInputSchema, createCreditNoteDraftSchema } from './invoices'

// invoice-payment-link-generation (wave-12) query helpers
export { stampPaymentLinkSentAt, getPaymentLinkEmailTemplate } from './invoice-payment-link'

// project-template-gallery query helpers (wave-6)
export { listTemplates, getTemplate, getTemplateTasks, createTemplate, updateTemplate, deleteTemplate, addTemplateTask, updateTemplateTask, deleteTemplateTask, instantiateTemplate, saveProjectAsTemplate, resolveFirstMemberWithRole } from './project-templates'
export { createTemplateSchema, updateTemplateSchema, createTemplateTaskSchema, updateTemplateTaskSchema, instantiateTemplateSchema, saveAsTemplateSchema } from './project-templates'
export type {
  TemplateObject,
  TemplateTaskObject,
  TemplateListPage as ProjectTemplateListPage,
  CreateTemplateInput,
  UpdateTemplateInput,
  CreateTemplateTaskInput,
  UpdateTemplateTaskInput,
  InstantiateTemplateInput,
  InstantiateResult,
  SaveAsTemplateInput,
} from './project-templates'

// crm-support-center query helpers (wave-6)
export { listTickets, getTicket, findTicketByThread, createTicket, updateTicket, softDeleteTicket, getTicketMessageById, getTicketMessage, autoReopenOnCustomerReply, listTicketMessages, createPlatformSupportMessage, updatePlatformSupportMessageMetadata, listPlatformSupportMessages, createTicketMessage, softDeleteTicketMessage, addTicketMessageAttachment, getTicketCategoryById, listTicketCategories, createTicketCategory, deleteTicketCategory, appendStatusTransitionMessage, closeStaleResolvedTickets } from './support'
export type { TicketObject, TicketMessageObject, TicketMessageAttachmentObject, TicketCategoryObject, TicketListPage, TicketFilters, PlatformSupportMessageRow, CreateTicketMessageInput, AddTicketAttachmentInput } from './support'
export { createTicketSchema, updateTicketSchema, replyTicketSchema, createTicketCategorySchema, ticketFiltersSchema } from '../validation/support'
export type { CreateTicketInput, UpdateTicketInput, ReplyTicketInput, CreateTicketCategoryInput, TicketFiltersInput } from '../validation/support'

// task-estimates-burndown query helpers (wave-6)
export { getProjectBurndown, getProjectEstimatedHours } from './burndown'
export { burndownQuerySchema } from './burndown'
export type { BurndownQuery, BurndownDay, BurndownResult } from './burndown'
export { getProjectTasksWithActualHours, getProjectEstimateSummary } from './projects'
export type { ProjectEstimateSummary } from './projects'

// project-hourly-budget query helpers (wave-6)
export { getProjectLoggedHours, getProjectBillingConfig, getProjectBudgetSummary, markBudgetAlertFired, getProjectOwnerIds, evaluateBudgetAlert } from './project-budget'

// time-reports query helpers (wave-6)
export { getTimeReportByPerson, getTimeReportByProject, getTimeReportByTask, getTimeReportTotals, getTimeReportPeopleOptions, formatHoursMinutes, secondsToHours } from './time-reports'
export type { TimeReportFilter, TimeReportByPersonRow, TimeReportByProjectRow, TimeReportByTaskRow, TimeReportTotals, TimeReportPersonOption } from './time-reports'

// ── Wave-7 query helpers ─────────────────────────────────────────────────────

// invoice-approval-workflow (P054) — leaf1
export { listPendingApprovals, approveInvoiceEnhanced, rejectInvoiceEnhanced, bulkApproveInvoices, countPendingApprovals, getInvoiceLinesForCopy } from './invoice-approvals'
export type { PendingApprovalItem, PendingApprovalsPage, BulkApproveResult } from './invoice-approvals'
export { approveInvoiceEnhancedSchema, rejectInvoiceEnhancedSchema, bulkApproveSchema, listPendingApprovalsSchema } from './invoice-approvals'

// invoice-draft-library (P055) — leaf1
export { listDraftInvoices, listTemplates as listDraftTemplates, createTemplate as createDraftTemplate, createInvoiceFromTemplate, countDraftInvoices, countTemplates as countDraftTemplates, getTemplate as getDraftTemplate, deleteTemplate as deleteDraftTemplate } from './invoice-drafts'
export type {
  DraftItem,
  DraftListPage,
  TemplateItem,
  TemplateListPage as DraftTemplateListPage,
} from './invoice-drafts'
export { createTemplateSchema as createDraftTemplateSchema, createFromTemplateSchema, listDraftsSchema, listTemplatesSchema as listDraftTemplatesSchema } from './invoice-drafts'

// recurring-invoices (P061) — leaf2
export { computeNextDate, computeInitialNextDate, previewNextDates, addDaysToDateString, generateInvoiceFromTemplate, listRecurringInvoiceTemplates, getRecurringInvoiceTemplate, countActiveRecurringTemplates, createRecurringInvoiceTemplate, updateRecurringInvoiceTemplate, cancelRecurringInvoiceTemplate, listDueRecurringTemplates, hasInvoiceForPeriod, advanceRecurringTemplate, getTenantOwnerUserId } from './recurring-invoices'
export type { CreateRecurringInvoiceInput, UpdateRecurringInvoiceInput, RecurringInvoiceTemplateRow, GenerateInvoiceFromTemplateResult, RecurringInvoiceTemplateListPage } from './recurring-invoices'
export { recurringInvoiceLineItemSchema, createRecurringInvoiceSchema, updateRecurringInvoiceSchema, listRecurringInvoiceTemplatesSchema } from './recurring-invoices'

// invoice-generation / bulk-generate (P058) — leaf2
export { getBulkGeneratePreview, createBulkGenerationJob, getBulkGenerationJobStatus, getCustomerBillableItems, listScopedCustomers, generateInvoicesForCustomers, processBulkInvoiceGenerationJob } from './invoice-generation'
export type { BulkGeneratePreviewInput, BulkGenerateInput, CustomerBillingPreview, BulkPreviewResult, CreateBulkGenerationJobInput, BulkJobResult, BulkJobStatus, LineItemDraft, CustomerBillableItems, BulkInvoiceQueueJob } from './invoice-generation'
export { bulkGeneratePreviewSchema, bulkGenerateSchema } from './invoice-generation'

// time-to-invoice (P064) — leaf3
export { listUnbilledTimeEntries, markTimeEntriesBilled, unbillTimeEntries, findAlreadyBilledEntries } from './time-invoice'
export type { UnbilledEntryFilter, UnbilledTimeEntry, UnbilledEntriesPage, MarkBilledInput } from './time-invoice'

// expense-to-invoice-line (P052) — leaf3
export { listBillableExpenses, getExpenseForInvoicing, listDraftInvoicesForCustomer, addExpenseToInvoiceLine } from './expense-invoice'
export type { BillableExpense, AddExpenseToInvoiceInput, AddExpenseToInvoiceResult } from './expense-invoice'

// project-milestones (P059) — leaf4
export {
  MilestoneInvoicedError,
  serializeMilestone,
  listMilestones,
  getMilestone,
  createMilestone,
  updateMilestone,
  completeMilestone,
  reopenMilestone,
  setMilestoneInvoice,
  deleteMilestone,
  getMilestoneSummary,
  createDepositMilestone,
  countIncompleteMilestones,
  listProjectMilestones,
  getMilestoneById,
} from './project-milestones'
export type { CreateMilestoneInput, UpdateMilestoneInput, MilestoneObject } from './project-milestones'

// project-analytics (P060) — leaf4
export { getProjectAnalytics } from './project-analytics'
export type {
  ProjectAnalytics,
  ProjectAnalyticsBudget,
  ProjectAnalyticsFinancials,
  ProjectAnalyticsMemberRow,
  ProjectAnalyticsWeekRow,
} from './project-analytics'

// project-lifecycle (archive/complete/reopen) — leaf4
export { getCompletionSummary, completeProject, archiveProject as archiveProjectLifecycle, reopenProject } from './project-archive'
export type { ProjectLifecycleStatus, LifecycleError, LifecycleResult } from './project-archive'

// project-gantt (wave-8 leaf 6)
export { getProjectGanttData, updateMilestoneDueDate, updateTaskDueDate } from './project-gantt'
export type { GanttProject, GanttMilestone, GanttTask, GanttData } from './project-gantt'

// contractor-payouts (P049) — leaf5
export { listContractors, getContractor, createContractor, updateContractor, deactivateContractor, listAssignments, createAssignment, updateAssignment, deleteAssignment, listContractorTimeEntries, listPayoutBills, getPayoutBillWithLines, generatePayoutBillDraft, updatePayoutBill, voidPayoutBill, listAllPayouts, findExpiringWithholdingCertificates, getWithholdingReport, getUnifiedWithholdingReport, listWithholdingCertificates, addWithholdingCertificate } from './contractors'
// contractor-portal (wave 8, Task 4)
export {
  createPortalSession,
  getPortalAccessStatus,
  findValidPortalSession,
  markPortalSessionUsed,
  getContractorForPortalRedeem,
} from './contractor-portal-sessions'
// contractor-portal (wave 8, Task 5)
export {
  resolveContractorApprovalRequirement,
  getContractorProfile,
  getContractorTimeEntry,
  assertContractorProjectAssignment,
  assertTaskBelongsToProject,
  computeContractorEntryTimes,
  listContractorTimeEntries as listContractorPortalTimeEntries,
  createContractorTimeEntry,
  updateContractorTimeEntry,
  deleteContractorTimeEntry,
  listContractorBills as listContractorPortalBills,
  ContractorPortalEntryNotFoundError,
  ContractorPortalEntryConflictError,
  ContractorPortalAssignmentError,
  ContractorPortalInactiveError,
} from './contractor-portal-time'
// contractor-portal (wave 8, Task 6)
export {
  resolveTenantLocale,
  listContractorPortalTimeExportRows,
  buildContractorPortalTimeLogCsv,
  buildContractorPortalTimeLogCsvExport,
  contractorPortalCsvHeaders,
} from './contractor-portal-export'
export type { ContractorPortalTimeExportRow } from './contractor-portal-export'
export { ContractorNotFoundError, PayoutBillNotFoundError, PayoutBillConflictError } from './contractors'
export { createContractorSchema, updateContractorSchema, listContractorsSchema, createAssignmentSchema, updateAssignmentSchema, generateBillSchema, updateBillSchema, voidBillSchema, listPayoutsSchema, listTimeForContractorSchema, withholdingReportSchema } from './contractors'

// marketing-leads-pipeline (P062) — leaf6
export { listPipelineStages, createPipelineStage, updatePipelineStage, deletePipelineStage, listLeads, getLead, createLead, updateLead, moveLead, archiveLead, linkLeadToCustomer, listLeadActivities, addLeadActivity, listLeadForms, getLeadForm, getLeadFormBySlug, getLeadFormSubmissionCount, listLeadFormSubmissions, createLeadForm, updateLeadForm, deleteLeadForm, createFormSubmissionAndLead, listLeadWebhooks, rebalanceLeadStage, getLeadWebhook, getLeadWebhookById, createLeadWebhook, updateLeadWebhook, deleteLeadWebhook, touchWebhookLastReceived, createWebhookLead, getMarketingOverview, listLeadRowsForTenant, upsertLeadRow } from './marketing'
// leads-detail-view (wave-13): detail + linked entities
export { getLeadDetail, listLinkedProposals, listLinkedContracts, listLinkedInvoices, listLinkedTasks } from './marketing'
export type { LeadObject, LeadActivityObject, LeadFormObject, LeadFormSubmissionObject, LeadWebhookObject, PipelineStageObject, OverviewData, LeadRowRecord, UpsertLeadRowInput } from './marketing'
export type { LeadDetailObject, LeadLinkedCounts, LinkedProposal, LinkedContract, LinkedInvoice, LinkedTask } from './marketing'
export { createLeadSchema, updateLeadSchema, moveLeadSchema, convertLeadSchema, leadFiltersSchema, addLeadActivitySchema, createLeadFormSchema, updateLeadFormSchema, publicFormSubmitSchema, createLeadWebhookSchema, updateLeadWebhookSchema, createPipelineStageSchema, updatePipelineStageSchema } from './marketing'

// lead-qualification-scoring (wave-14)
export { getLeadScoringCriteria, upsertLeadScoringCriteria, computeAndSaveLeadScore, getLeadScoreBreakdown, listLeadsForScoreRefresh, listAllActiveLeadTenantPairs, leadScoringCriteriaSchema, DEFAULT_LEAD_SCORING_CRITERIA } from './lead-scoring'
export type { LeadScoringCriteria, LeadScoreResult } from './lead-scoring'

// lead-lost-re-engagement (wave-14)
export { reopenLead, selectDueReengagementLeads, markReengagementNotified, getLostReasons, updateLostReasons } from './marketing'
export type { DueReengagementLead } from './marketing'

// ticket-sla-escalation (P063) — leaf7
export { listSlaPolicies, getSlaPolicyById, getSlaPolicyByPriority, updateSlaPolicy, seedSlaPolicies, getSlaEnabled, computeAndSetDueAt, markFirstResponse, findAndMarkBreachedTickets } from './ticket-sla'
export type { SlaPolicyObject, BreachedTicketRef, UpdateSlaPolicyInput } from './ticket-sla'
export { updateSlaPolicySchema, slaPrioritySchema } from './ticket-sla'

// settings-projects (P062) — leaf7
export { getProjectSettings, updateProjectSettings } from './settings-projects'
export type { ProjectSettingsObject, ProjectSettingsInput } from './settings-projects'
export { projectSettingsSchema } from './settings-projects'

// data-import (P040) — leaf8
export { listImportJobs, getImportJob, createImportJob, setImportJobProcessing, updateImportJobMappings, completeImportJob, insertImportJobResult, listImportJobResults, countImportJobResultsByStatus, deleteImportJob } from './data-import'
export type { ImportJobObject, ImportJobResultObject, CreateImportJobInput, InsertImportJobResultInput } from './data-import'

// unified-attachments (leaf8)
export { listAttachmentsForEntity, getAttachment, insertAttachment, softDeleteAttachment, hardDeleteAttachmentRow, insertDraftTaskAttachment, reparentTaskAttachments } from './attachments'
export type { AttachmentEntityType, AttachmentObject, AttachmentRow, CreateAttachmentInput, InsertDraftAttachmentInput } from './attachments'

// customer-dedup-merge (P067) — leaf9
export {
  scanForDuplicates,
  listMergeSuggestions,
  dismissSuggestion,
  mergeCustomers,
  MergeNotFoundError,
  AlreadyMergedError,
} from './customer-dedup'
export type { MergeSuggestion, MergeSuggestionsPage, MergeRequest, MergeResult } from './customer-dedup'

// invoice-adapters (P056) — leaf9
export { getAdapterConfig, upsertAdapterConfig, removeAdapterConfig, listAdapterConfigs, logSyncEvent, listSyncLogs, getPendingInvoices, getInvoiceAdapterSettings, getInvoiceForAdapterPush, updateInvoiceAdapterSettings } from './invoice-adapters'
export type { AdapterConfig, AdapterConfigSummary, SyncLog, SyncLogsPage, InvoiceAdapterSettings, InvoicePushPayload } from './invoice-adapters'
export type { ILInvoiceProvider } from '../schema/invoice-adapters'
export { IL_INVOICE_PROVIDERS } from '../schema/invoice-adapters'

// home-dashboard (P053) — leaf9
export { getDashboardData, dismissChecklist } from './dashboard'

// bulk-operations (wave-8 leaf 2)
export {
  bulkUpdateInvoiceStatus,
  bulkArchiveCustomers,
  bulkDeleteExpenses,
  bulkUpdateProjectStatus,
  bulkInvoiceStatusSchema,
  bulkCustomerArchiveSchema,
  bulkExpenseDeleteSchema,
  bulkProjectStatusSchema,
} from './bulk-operations'
export type { BulkInvoiceStatusResult, BulkInvoiceStatusOptions } from './bulk-operations'
export type {
  DashboardResponse,
  DashboardModules,
  DashboardDataContext,
  ActivityEvent,
  CalendarEvent,
  TaskDue,
  ChecklistItem,
} from './dashboard'

// billing-module (wave-8 leaf 1)
export {
  getTenantBilling,
  getPaymentMethods,
  getBillingHistory,
  updateBillingEmail,
} from './billing'
export type { BillingInfo, PaymentMethod, BillingHistoryItem, BillingHistoryPage } from './billing'

// lead-form-builder + lead-to-customer-conversion (wave-8 leaf5)
export { convertLeadToCustomer } from './lead-conversion'
export type { ConvertLeadResult, ConvertLeadCustomerData } from './lead-conversion'

// wave-8: saved-list-filters (leaf9)
export { listSavedFilters, createSavedFilter, deleteSavedFilter, createSavedFilterSchema } from './saved-filters'
export type { SavedFilterObject, CreateSavedFilterInput } from './saved-filters'

// wave-8: telegram-bot (leaf9)
export { getTelegramChats, linkTelegramChat, unlinkTelegramChat, getTelegramChatByChatId } from './telegram'
export type { TelegramChatObject } from './telegram'

// wave-8: contracts-esignature (leaf4)
export {
  listContracts,
  getContract,
  getContractPublic,
  createContract,
  sendContract,
  signContract,
  voidContract,
  ContractNotFoundError,
} from './contracts'
export type { Contract, ContractListResponse, ContractActorContext } from './contracts'

// wave-9: calendar-task-creation (leaf2)
export {
  createTaskFromCalendarEvent,
  getCalendarEventTasks,
} from './calendar-tasks'
export type { CreateTaskFromEventInput } from './calendar-tasks'

// wave-9: contract-to-invoice (leaf2)
export {
  generateInvoiceFromContract,
  getContractInvoiceId,
} from './contract-invoice'

// profitability-reports (wave-8 leaf 7)
export {
  getProjectProfitability,
  getTenantProfitability,
  getCustomerProfitability,
  getClientProfitability,
} from './profitability'
export type {
  ProfitabilityListRow,
  ProfitabilitySummary,
  ProjectProfitabilityDetail,
  ProjectProfitabilityListRow,
  CustomerProfitabilityDetail,
  TenantProfitabilityResult,
} from './profitability'

// revenue-forecasting (wave-8 leaf 7)
export { getRevenueForecast } from './forecasting'
export {
  buildForecastWindow,
  summarizeCommittedInvoices,
  summarizeProjectedLeads,
  summarizeScheduledTemplates,
} from './forecasting'
export type { ForecastWindow } from './forecasting'

// time-entry-locking (wave-8 leaf 8)
export { lockTimeEntries, unlockTimeEntries, getLockedEntries } from './time-locking'
export type { LockResult, LockedEntryRow } from './time-locking'

// team-time-overview (wave-8 leaf 8)
export { getTeamTimeOverview, getMemberTimeDetail } from './team-time'
export type {
  TeamMemberOverview,
  TeamMemberProjectBreakdown,
  TeamTimeOverviewResult,
  MemberTimeDetailResult,
  MemberProjectGroup,
  MemberDayGroup,
  MemberDayEntry,
} from './team-time'

// ── Wave-9 query helpers ─────────────────────────────────────────────────────

// billing-plans-management-ui (P083) — leaf1
export {
  listBillingPlans,
  getBillingPlan,
  createBillingPlan,
  updateBillingPlan,
  archiveBillingPlan,
  BillingPlanNotFoundError,
  BillingPlanArchivedError,
} from './billing-plans'
export type { BillingPlanListRow, CreateBillingPlanInput, UpdateBillingPlanInput } from './billing-plans'

// marketing-catalogs-campaigns (wave-9 leaf3)
export {
  listCatalogItems,
  searchCatalogItems,
  getCatalogItem,
  createCatalogItem,
  updateCatalogItem,
  deleteCatalogItem,
  listCatalogCategories,
  createCatalogItemSchema,
  updateCatalogItemSchema,
} from './catalog'
export type { CatalogItemObject, CreateCatalogItemInput, UpdateCatalogItemInput } from './catalog'

export {
  listProposals,
  getProposal,
  createProposal,
  updateProposal,
  deleteProposal,
  sendProposal,
  acceptProposal,
  rejectProposal,
  createProposalSchema,
  updateProposalSchema,
  // wave-11: proposal-editor
  createProposalEditorSchema,
  updateProposalEditorSchema,
  proposalContentSchema,
  createProposalDraft,
  updateProposalDraft,
  sendProposalDraft,
  // wave-11: public-proposal-view
  getProposalByPublicToken,
  recordProposalView,
  acceptProposalByToken,
  rejectProposalByToken,
  // wave-11: proposal-templates
  listProposalTemplates,
  createProposalTemplate,
  deleteProposalTemplate,
  // wave-12: proposal-expiry-deadline
  extendProposal,
} from './proposals'
export type {
  ProposalObject,
  ProposalLineItem,
  CreateProposalInput,
  UpdateProposalInput,
  // wave-11
  CreateProposalEditorInput,
  UpdateProposalEditorInput,
  ProposalPublicData,
  ProposalTemplateObject,
} from './proposals'

export {
  listCampaigns,
  getCampaign,
  createCampaign,
  updateCampaign,
  activateCampaign,
  listCampaignRowsForTenant,
  upsertCampaignRow,
  createCampaignSchema,
  updateCampaignSchema,
} from './campaigns'
export type { CampaignObject, CampaignRowRecord, CreateCampaignInput, UpdateCampaignInput, UpsertCampaignRowInput } from './campaigns'

// tenant-portals (wave-9 leaf 5): customer portal query helpers
export {
  findCustomerContactByEmail,
  getPortalDashboard,
  getPortalInvoices,
  getPortalProjects,
  listPortalProjectsDetailed,
  getPortalProjectDetail,
  listPortalTicketSummaries,
  getPortalTickets,
  getPortalTicketForCustomer,
  createPortalTicket,
  createPortalTicketWithMessage,
  listPortalProposals,
  getPortalProfile,
  updatePortalProfile,
  updatePortalUserPassword,
  createPortalTicketSchema,
  PORTAL_INVOICE_STATUSES,
} from './customer-portal'
export type {
  PortalInvoice,
  PortalProject,
  PortalProjectListItem,
  PortalDashboard,
  PortalTicketListItem,
  PortalTicket,
  PortalContact,
  PortalProposalListItem,
  PortalProfileRow,
  PortalInvoiceStatus,
  CreatePortalTicketInput,
} from './customer-portal'

// tenant-portals (wave-9 leaf 5): portal auth helpers
export {
  generatePortalToken,
  validatePortalToken,
} from './portal-auth'
export type { PortalTokenResult, PortalCustomerSession } from './portal-auth'

// multi-currency (wave-10 leaf 4): exchange rate query helpers
export {
  getExchangeRate,
  upsertExchangeRate,
  convertAmount,
  listExchangeRates,
} from './exchange-rates'
export type { ExchangeRate, NewExchangeRate } from '../schema/exchange-rates'

// wave-10 leaf 3: bank-statement-import
export { parseBankStatement, importBankTransactions } from './bank-import'
export type { BankFormat, ParsedTransaction, ImportSummary } from './bank-import'

// wave-10 leaf 3: recurring-expenses
export {
  listRecurringExpenses,
  createRecurringExpense,
  updateRecurringExpense,
  deactivateRecurringExpense,
  generateDueExpenses,
  createRecurringExpenseSchema,
  updateRecurringExpenseSchema,
} from './recurring-expenses'
export type {
  RecurringExpenseTemplateRow,
  CreateRecurringExpenseInput,
  UpdateRecurringExpenseInput,
} from './recurring-expenses'

// wave-10 leaf 3: mileage-logbook
export {
  listMileageEntries,
  createMileageEntry,
  getMileageSummary,
  createMileageEntrySchema,
  ITA_RATE_PER_KM,
} from './mileage'
export type {
  MileageEntryRow,
  MileageSummary,
  CreateMileageEntryInput,
} from './mileage'

// wave-10 leaf 8: reports-analytics
export {
  getRevenueByPeriod,
  getExpensesByCategory,
  getTopCustomers,
  getTeamProductivity,
  getOverdueReport,
} from './analytics'
export type {
  RevenuePeriodRow,
  ExpenseCategoryRow,
  TopCustomerRow,
  TeamProductivityRow,
  OverdueInvoiceRow,
} from './analytics'

// wave C: reports-analytics custom dashboards
export {
  WIDGET_TYPES,
  listDashboardsForUser,
  ensureDefaultDashboard,
  getDashboardForUser,
  getDashboardWithWidgets,
  createDashboard,
  updateDashboard,
  deleteDashboard,
  addDashboardWidget,
  updateDashboardWidget,
  deleteDashboardWidget,
} from './dashboards'
export type {
  WidgetType,
  DashboardWithWidgets,
  AddWidgetInput,
} from './dashboards'
export { resolveWidgetData } from './widget-analytics'
export type {
  WidgetDateRange,
  WidgetFilters,
  WidgetQueryEnv,
  WidgetDataPayload,
  WidgetRow,
} from './widget-analytics'

// wave-10 leaf 8: data-export-gdpr
export {
  exportTenantData,
  anonymizeCustomer,
  createExportJob,
  getExportJobStatus,
  setExportJobProcessing,
  completeExportJob,
  failExportJob,
} from './data-export'
export type {
  ExportJobObject,
  TenantExportData,
} from './data-export'

// wave-10 leaf 1: calendar-integration-settings-ui
export {
  listCalendarSettingsConnections,
  getCalendarSettingsConnection,
  updateCalendarConnectionPrefs,
  setCalendarConnectionStatus,
} from './settings-calendar'
export type {
  CalendarProvider as SettingsCalendarProvider,
  CalendarSyncDirection as SettingsCalendarSyncDirection,
  CalendarConnectionStatus as SettingsCalendarConnectionStatus,
  CalendarConnectionPublic,
  CalendarListItemPublic,
  CalendarConnectionPrefsPatch,
} from './settings-calendar'
export type {
  CalendarSettingsObject,
  CalendarSettingsPatch,
  CalendarConnection,
  CalendarSyncDirection,
} from './settings-calendar'

// wave-10 leaf 1: invoice-settings-page
export { getInvoiceSettings, updateInvoiceSettings } from './settings-invoices'
export type { InvoiceSettingsObject, InvoiceSettingsPatch, InvoiceTaskStatusTrigger } from './settings-invoices'
export {
  processRetainerInvoiceJob,
  processFixedDepositJob,
  processTaskStatusInvoiceJob,
  processInvoiceGenerateJob,
  maybeEnqueueTaskStatusInvoice,
  enqueueTaskStatusInvoicesForBulk,
  enqueueFixedDepositIfConfigured,
  autoGenDedupKey,
  autoGenDedupeNote,
} from './invoice-automation'
export type { RetainerInvoiceJob, InvoiceGenerateJob, InvoiceQueueBinding } from './invoice-automation'

// wave-10 leaf 7: customer-portal-access-control
export {
  listCustomerPortalAccess,
  enablePortalAccess,
  disablePortalAccess,
  sendPortalInvite,
  enablePortalAccessSchema,
  sendPortalInviteSchema,
  portalModuleSchema,
} from './portal-access'
export type {
  CustomerPortalAccessRow,
  PortalInviteResult,
  PortalModule,
  EnablePortalAccessInput,
  SendPortalInviteInput,
} from './portal-access'

// wave-10 leaf 7: white-label-api
export {
  getWhiteLabelConfig,
  upsertWhiteLabelConfig,
  getWhiteLabelByDomain,
  initiateWhiteLabelDomainVerification,
  upsertWhiteLabelSchema,
} from './white-label'
export type {
  WhiteLabelConfigRow,
  UpsertWhiteLabelInput,
} from './white-label'

// wave-10 leaf 7: subscription-cancellation-flow
export {
  initiateCancellation,
  completeCancellation,
  retentionOffer,
  initiateCancellationSchema,
  cancellationReasonSchema,
} from './subscription-cancellation'
export type {
  CancellationReason,
  InitiateCancellationInput,
  RetentionOffer,
  RetentionOfferType,
} from './subscription-cancellation'

// wave-10 leaf 6: email-marketing-sequences
export {
  listSequences,
  getSequence,
  createSequence,
  updateSequence,
  deleteSequence,
  listSequenceSteps,
  createSequenceStep,
  updateSequenceStep,
  deleteSequenceStep,
  listEnrollments,
  enrollInSequence,
  getDueEnrollments,
  getAllDueEnrollments,
  advanceEnrollment,
  countEnrollments,
  createSequenceSchema,
  updateSequenceSchema,
  createSequenceStepSchema,
  updateSequenceStepSchema,
  enrollInSequenceSchema,
} from './email-sequences'
export type {
  EmailSequenceObject,
  EmailSequenceStepObject,
  EmailSequenceEnrollmentObject,
  CreateSequenceInput,
  UpdateSequenceInput,
  CreateSequenceStepInput,
  UpdateSequenceStepInput,
  EnrollInSequenceInput,
} from './email-sequences'

// wave-10 leaf 6: lead-to-proposal-flow
export { createProposalFromLead } from './lead-proposal'
export type { CreateProposalFromLeadResult } from './lead-proposal'

// wave-10 leaf 5: ita-einvoice
export {
  getEinvoiceConfig,
  getEinvoiceConfigSummary,
  updateEinvoiceConfig,
  getEinvoiceStatus,
  markInvoiceAsSubmitted,
  updateEinvoiceConfigSchema,
} from './einvoice'
export type { EinvoiceConfig, EinvoiceConfigSummary, EinvoiceStatus, UpdateEinvoiceConfigInput } from './einvoice'

// wave-10 leaf 5: payment-gateway-adapters
export {
  getPaymentGatewayConfig,
  getPaymentGatewayConfigMasked,
  upsertPaymentGatewayConfig,
  getPaymentLinkForInvoice,
  upsertPaymentGatewaySchema,
} from './payment-gateways'
export type { PaymentGatewayConfigFull, PaymentGatewayConfigMasked, UpsertPaymentGatewayInput } from './payment-gateways'
export { PAYMENT_GATEWAYS } from '../schema/payment-gateways'
export type { PaymentGateway } from '../schema/payment-gateways'

// wave-10 leaf 6: proposal-to-contract
export { createContractFromProposal } from './proposal-contract'
export type { CreateContractFromProposalResult } from './proposal-contract'

// wave-10 leaf 10: time-approval-workflow
export {
  listTimeApprovalEntries,
  approveTimeEntry,
  rejectTimeEntry,
  bulkReviewTimeEntries,
  resubmitTimeEntry,
  exportApprovedTimeEntries,
  buildPayrollExportCsv,
  listTimeApprovalEntriesSchema,
  approveTimeEntrySchema,
  rejectTimeEntrySchema,
  bulkReviewTimeEntriesSchema,
  exportApprovedTimeEntriesSchema,
} from './time-approval'
export type { TimeApprovalListItem, PayrollExportRow } from './time-approval'

// wave-10 leaf 6: proposals.contractId — re-exported serializer (internal)
export { serializeProposalRow } from './proposals'

// wave-13: proposals-list paginated query
export { listProposalsPaginated } from './proposals'
export type { ProposalListItem, ProposalListOpts, ProposalListPage } from './proposals'

// wave-11: customer-portal-settings-ui (spec 136)
export {
  getPortalSettings,
  DEFAULT_PORTAL_VISIBILITY,
  upsertPortalSettings,
  listTenantPortalUsers,
  revokePortalUser,
  touchPortalUserLogin,
  resolvePortalVisibility,
} from './settings-portal'
export type { PortalSettingsDTO, UpdatePortalSettingsBody, PortalUserRow } from './settings-portal'

// wave-11: settings-customers
export {
  getCustomerSettings,
  updateCustomerSettings,
  resolveAutoInviteMode,
} from './settings-customers'
export type { CustomerSettingsDTO, UpdateCustomerSettingsBody } from './settings-customers'

// wave-11: settings-roles
export {
  listCustomRoles,
  createCustomRole,
  updateCustomRole,
  deleteCustomRole,
  TENANT_PERMISSION_VOCABULARY,
  SystemRoleImmutableError,
  RoleNameConflictError,
  RoleHasMembersError,
  RoleNotFoundError,
  UnknownPermissionKeyError,
} from './roles'
export type { CustomRoleDTO, TenantPermissionKey } from './roles'

// wave-11: partial-payment-recording
export {
  listInvoicePayments,
  getInvoiceBalance,
  recordInvoicePayment,
  reverseInvoicePayment,
  recordPaymentInputSchema,
  recordPaymentUserInputSchema,
  reversePaymentInputSchema,
  ReceiptIssuedError,
} from './invoice-payments'
export type { RecordPaymentInput, ReversePaymentInput } from './invoice-payments'

// wave-11: payment-retry-dunning
export {
  listDunningSchedules,
  upsertDunningSchedule,
  deleteDunningSchedule,
  appendDunningLog,
  listDunningLog,
  getDunningSuspendAccess,
  isDunningStepAlreadySent,
  upsertDunningScheduleSchema,
  deleteDunningScheduleSchema,
} from './dunning'
export type {
  DunningScheduleObject,
  DunningLogObject,
  UpsertDunningScheduleInput,
} from './dunning'

// wave-11: invoice-pdf-customization
export {
  getInvoicePdfTemplate,
  updateInvoicePdfTemplate,
  invoicePdfTemplateSchema,
  INVOICE_PDF_TEMPLATE_DEFAULTS,
} from './invoice-pdf-template'
export type {
  InvoicePdfTemplate,
  InvoicePdfLayout,
  InvoicePdfDateFormat,
  UpdateInvoicePdfTemplate,
  InvoicePdfTemplatePatch,
} from './invoice-pdf-template'

// wave-11: proposal-to-invoice-direct
export {
  getProposalInvoiceLink,
  createInvoiceFromProposal,
  createInvoiceFromProposalSchema,
} from './proposal-invoice'
export type {
  ProposalInvoiceLinkResult,
  CreateInvoiceFromProposalResult,
  CreateInvoiceFromProposalInput,
} from './proposal-invoice'

// wave-11 leaf-C: portal-file-sharing
export {
  listPortalFilesForStaff,
  listPortalFilesForPortal,
  getPortalFileById,
  createPortalFile,
  updatePortalFile,
  deletePortalFile,
  InvalidUploaderError,
} from './portal-files'
export type {
  PortalFile,
  PortalFileListItem,
  PortalFilePublicItem,
  NewPortalFile,
  UpdatePortalFileInput,
} from './portal-files'

// wave-11 leaf-C: public-catalog-page
export { getCatalogShareByToken } from './catalog-public'
export type { CatalogPublicData } from './catalog-public'

// wave-11 leaf-C: contract-signing-page
export {
  getSignatoryByToken,
  signContract as signContractByToken,
  declineContract,
  recordContractView,
  recordContractAuditEvent,
} from './contract-signing'
export type { SignatoryWithContract, SignContractInput } from './contract-signing'

// wave-12: multi-signatory-coordination
export {
  getContractTenantScoped,
  listSignatories,
  getSignatory,
  checkSignatoryEmailCollision,
  bulkUpsertSignatories,
  markManualReminderSent,
  resendSignatoryLink,
  replaceSignatory,
  markSignatoryReminderSent,
  appendContractAuditLog,
} from './contract-signatories'
export type {
  ContractSignatoryRow,
  BulkUpsertSignatoryInput,
} from './contract-signatories'

// wave-11 leaf-D: webhook-endpoint-detail
export {
  listWebhookEndpoints,
  getWebhookEndpoint,
  getWebhookEndpointWithSecret,
  createWebhookEndpoint,
  updateWebhookEndpoint,
  updateWebhookSecret,
  deleteWebhookEndpoint,
  listWebhookDeliveries,
  getWebhookDelivery,
  insertWebhookDelivery,
  updateWebhookDelivery,
  insertWebhookDeliveryLog,
  listWebhookDeliveryLogs,
  deleteOldWebhookDeliveryLogs,
  getApiKeyByHash,
  listTenantApiKeys,
  createTenantApiKey,
  revokeTenantApiKey,
  updateApiKeyLastUsed,
  // wave-12: api-usage-quota-ui
  getApiKeyForTenant,
  updateApiKeyMonthlyQuota,
  createWebhookSchema,
  updateWebhookSchema,
} from './webhooks'
export type {
  WebhookEndpointObject,
  WebhookDeliveryObject,
  WebhookDeliveryLogObject,
  TenantApiKeyObject,
  CreateWebhookInput,
  UpdateWebhookInput,
} from './webhooks'

// wave-11 leaf-D: audit-compliance (partitioned audit_log — distinct from tenant_audit_log)
export {
  listAuditLog as listAuditLogV2,
  writeAuditLog,
  listAuditLogSystem,
  deleteOldAuditLogs as deleteExpiredAuditLogs,
} from './audit-compliance'
export type { AuditLogRow, AuditListOptions } from './audit-compliance'

// wave-11 leaf-D: tenant-export-jobs (uses tenantExportJobs table; distinct from data-export.ts)
export {
  createTenantExportJob,
  getTenantExportJobById,
  markTenantExportJobStatus,
} from './tenant-export-jobs'
export type { TenantExportJobObject } from './tenant-export-jobs'

// wave-11 leaf-E: expense-approval-workflow
export {
  resolveApprovalStatus,
  listPendingApprovals as listPendingExpenseApprovals,
  approveExpense,
  rejectExpense,
  isExpenseApprover,
} from './expense-approvals'
export type { ApprovalStatus, ApprovalQueueItem } from './expense-approvals'

// wave-11 leaf-E: contractor-settings
export {
  getContractorSettings,
  updateContractorSettings,
} from './settings-contractors'
export type { ContractorSettingsDTO, UpdateContractorSettingsBody } from './settings-contractors'

// wave-11 leaf-E: email-template-editor
export {
  getTenantEmailTemplate,
  listTenantEmailTemplates,
  saveTenantEmailTemplate,
  resetTenantEmailTemplate,
} from './email-templates'
export type { TenantEmailTemplateRow, EmailTemplateListItem } from './email-templates'

// wave-11 leaf-E: field-level-permissions
export {
  getTenantFieldRules,
  saveTenantFieldRules,
} from './field-permissions'
export type { FieldPermissionRuleRow } from './field-permissions'

// wave-11 leaf-E: vendors-suppliers
export {
  listVendors,
  getVendor,
  createVendor,
  updateVendor,
  archiveVendor,
  suggestVendors,
  getVendorYtdSpend,
} from './vendors'
export type { VendorRow, VendorListItem, VendorWithStats, CreateVendorInput, UpdateVendorInput } from './vendors'

// wave-11 leaf-E: timezone-handling
export {
  getTenantTimezone,
  setUserTimezone,
  setTenantTimezone,
} from './timezone'

// wave-12: ar-aging-report
export { buildArAgingReport, buildArAgingCustomerStatement, assignAgingBucket } from './ar-aging'
export type { ArAgingCustomerStatementData, ArAgingStatementInvoice } from './ar-aging'

// wave-12: proposal-expiry-deadline
export { getProposalSettings, updateProposalSettings } from './settings-proposals'
export type { ProposalSettingsObject } from './settings-proposals'

// wave-12: proposal-expiry-deadline cron helpers
export {
  expireOverdueProposals,
  getOwnerAdminUserIds,
  insertProposalExpiredNotification,
  insertProposalExpiringNotification,
  revertLeadToQualifiedIfNoLiveProposal,
  findExpiringProposals,
} from './proposal-expiry-cron'
export type { ExpiredProposalRow, ExpiringProposalRow } from './proposal-expiry-cron'

// wave-12: contract-renewal-amendment
export {
  renewContract,
  amendContract,
  getContractLineage,
  getExpiringContracts,
} from './contract-renewal'
export type {
  RenewalContract,
  ContractLineage,
  ContractLineageItem,
  ExpiringContract,
  RenewContractInput,
  AmendContractInput,
} from './contract-renewal'


// wave-12: operational-audit-trail (spec 50)
export {
  computeDiff,
  captureEntityChange,
  listEntityHistory,
  serializeEntityChange,
  TRACKED_ENTITIES,
  HISTORY_API_ENTITIES,
} from './entity-history'
export type {
  CaptureEntityChangeParams,
  EntityChangeRecord,
  EntityHistoryOptions,
  EntityHistoryPage,
} from './entity-history'

// wave-12: bad-debt-writeoff
export {
  writeOffInputSchema,
  recordRecoveryInputSchema,
  reclaimPatchInputSchema,
  performWriteOff,
  performRecovery,
  listReclaims,
  patchReclaim,
  getBadDebtReport,
  getBadDebtSettings,
  updateBadDebtSettings,
  WriteOffNotFoundError,
  WriteOffIneligibleError,
  WriteOffThresholdError,
} from './bad-debt'
export type {
  WriteOffInput,
  RecordRecoveryInput,
  ReclaimPatchInput,
  WriteOffResult,
  RecoveryResult,
  ReclaimWithContext,
} from './bad-debt'

// payment-reconciliation (wave-12)
export {
  listOutstandingInvoices,
  listUnmatchedPayments,
  createUnmatchedPayment,
  deleteUnmatchedPayment,
  matchUnmatchedPayment,
  AlreadyMatchedError,
  InvalidInvoiceStatusError,
} from './reconcile'
export type {
  OutstandingInvoice,
  OutstandingInvoicesPage,
  ListOutstandingOptions,
  CreateUnmatchedPaymentInput,
  MatchResult,
  UnmatchedPaymentObject,
} from './reconcile'
// payment-reconciliation: tx-aware helper for external orchestrators
export { recordInvoicePaymentTx } from './invoice-payments'

// wave-12: invoice-receipt-document
export {
  listReceipts,
  getReceiptWithLines,
  listReceiptsForInvoice,
  issueStandaloneReceipt,
  issueInvoiceReceipt,
  voidReceipt,
  setReceiptPdfR2Key,
  nextReceiptNumber,
  serializeReceiptRow,
  serializeReceiptLine,
  issueStandaloneReceiptSchema,
  issueInvoiceReceiptSchema,
  voidReceiptSchema,
  listReceiptsSchema,
  ReceiptNotFoundError,
  ReceiptConflictError,
} from './receipts'
export type {
  IssueStandaloneReceiptInput,
  IssueInvoiceReceiptInput as IssueInvoiceReceiptQueryInput,
  IssueInvoiceReceiptResult,
  VoidReceiptInput as VoidReceiptQueryInput,
  ListReceiptsInput,
} from './receipts'


// wave-12: oauth-authorization-code query helpers
export {
  getOAuthClientByClientId,
  getOAuthClientById,
  listOAuthClientsQuery,
  createOAuthClientRecord,
  updateOAuthClientRecord,
  insertAuthorizationCode,
  lookupAuthorizationCode,
  markAuthorizationCodeUsed,
  insertTokenPair,
  lookupRefreshToken,
  rotateOAuthRefreshToken,
  revokeOAuthTokenFamily,
  revokeAccessTokenByHash,
  revokeRefreshTokenByHash,
  revokeAccessTokensByFamily,
  revokeClientConnectionTokens,
  resolveOAuthAccessToken,
  listOAuthConnectionsForUser,
  touchOAuthConnectionLastUsed,
} from './oauth'
export type {
  OAuthClientRow,
  OAuthAuthorizationCodeRow,
  OAuthAccessTokenRow,
  OAuthRefreshTokenRow,
  OAuthConnectionRow,
  ResolvedOAuthToken,
  OAuthConnectionView,
  InsertTokenPairArgs,
  RotateRefreshArgs,
} from './oauth'

// wave-12: activity-timeline helpers (append writers + soft-delete)
export {
  appendInvoiceActivity,
  appendProjectActivity,
  appendCustomerActivity,
  appendVendorActivity,
  getCustomerActivityNote,
  softDeleteCustomerActivity,
  getInvoiceActivityNote,
  softDeleteInvoiceActivity,
  getProjectActivityNote,
  softDeleteProjectActivity,
  getVendorActivityNote,
  softDeleteVendorActivity,
} from './activities'
export type { ActivityNoteRow } from './activities'

// wave-13: settings-contracts
export {
  getContractSettings,
  updateContractSettings,
  CrossTenantTemplateError,
} from './settings-contracts'

// wave-13: expense-ocr-correction-ux
export {
  listReviewQueue,
  approveOcrExpense,
  reprocessExpense,
  correctExpense,
  voidExpense,
  getExpenseApproverInfo,
} from './expense-ocr-corrections'
export type {
  ApproveOcrExpenseArgs,
  CorrectExpenseArgs,
} from './expense-ocr-corrections'

// wave-13: session-security query helpers
export {
  createSession,
  getSessionByTokenHash,
  touchSession,
  revokeSession,
  revokeSessionByTokenHash,
  revokeOtherUserSessions,
  revokeAllSessionsForUser,
  revokeAllTenantSessions,
  listUserSessions,
  listTenantUserSessionSummaries,
  countActiveSessions,
  sweepExpiredSessions,
  cleanupIdleSessions,
  getTenantSecuritySettings,
  upsertTenantSecuritySettings,
} from './sessions'
export type {
  UserSessionRow,
  NewUserSession,
  TenantSecuritySettingsRow,
  CreateSessionArgs,
  RevokeSessionsResult,
  TenantSecuritySettingsPatch,
  TenantUserSessionSummary,
} from './sessions'

// wave-13: invoice-payment-reminders query helpers
export {
  parseReminderSchedule,
  computeNextReminder,
  getTenantReminderSettings,
  updateTenantReminderSettings,
  selectReminderDueInvoices,
  advanceInvoiceReminder,
  setInvoiceReminderState,
  disableInvoiceReminders,
  resolveReminderRecipient,
  DEFAULT_REMINDER_SCHEDULE,
} from './invoice-reminders'
export type { ReminderStage, NextReminder, ReminderSettings, ReminderDueInvoice } from './invoice-reminders'

// wave-13: invoice-email-history query helpers
export {
  insertEmailEvent,
  listEmailEventsByInvoice,
  hasRecentOpenEvent,
  getLatestRecipientStatus,
  getLastSendRecipients,
  getLastSentEventForInvoice,
} from './invoice-email-events'
export type {
  InvoiceEmailEventType,
  InvoiceEmailEventRow,
  InvoiceEmailEventWithSender,
} from './invoice-email-events'

// wave-13: reports-navigation-hub (spec 103)
export {
  listReportShortcuts,
  createReportShortcut,
  deleteReportShortcut,
  getReportsSummary,
  createReportShortcutInputSchema,
  REPORT_TYPES,
  getRevenueLedger,
  getInvoiceReport,
  getPaymentReport,
} from './reports'
export type {
  ReportType,
  ReportsSummary,
  ReportsSummaryScope,
  ReportsSummaryEnv,
  CreateReportShortcutInput,
  RevenueLedgerReport,
  RevenueLedgerRow,
  RevenueLedgerTotals,
  RevenueLedgerFilters,
  InvoiceReport,
  InvoiceReportRow,
  InvoiceReportSummary,
  InvoiceReportTotals,
  InvoiceReportFilters,
  PaymentReport,
  PaymentReportRow,
  PaymentReportSummary,
  PaymentReportTotals,
  PaymentReportFilters,
} from './reports'

// wave-13: financial-statements (spec 170) — P&L and Cash Flow aggregation services
export { getProfitLoss, getCashFlow } from '../reports'
export type { ProfitLossReport, CashFlowReport } from '../reports'

// wave-13: uniform-format-export (spec 180) — job lifecycle helpers
export {
  uniformExportJobs,
  createUniformExportJob,
  getUniformExportJob,
  listUniformExportJobs,
  setUniformExportJobRunning,
  setUniformExportJobDone,
  setUniformExportJobError,
  updateUniformExportJobDownloadExpiry,
} from './uniform-export'
export type { UniformExportJobRow, NewUniformExportJob } from './uniform-export'

// wave-14: settings-kb — KB settings, spaces management, review queue
export {
  getKbSettings,
  upsertKbSettings,
  KbDefaultSpaceCrossTenantError,
} from './kb-settings'
export {
  listSpacesWithCounts,
  renameSpace,
  reorderSpace,
  deleteSpaceIfEmpty,
  nextSpacePosition,
  KbSpaceHasArticlesError,
  KbSpaceNotFoundError,
  KbVaultSpaceDeleteError,
} from './kb-spaces'
export type { KbSpaceListItem } from './kb-spaces'
export {
  listPendingReview,
  submitForReview,
  approveArticle,
  rejectArticle,
  getLatestRejectionFeedback,
  KbArticleNotFoundError,
  KbArticleStatusError,
} from './kb-review'
export type { KbReviewItem, KbReviewPage, KbArticleRejection } from './kb-review'

// wave-14: israeli-tax-reports (spec 176)
export {
  getPcn874Report,
  getAnnualIncomeSummary,
  getAnnualSummaryDetail,
  getAdvanceTaxEstimate,
  getTaxSettings,
  updateTaxSettings,
} from './tax-reports'

// wave-15: settings-crm (spec 2026-06-01-settings-crm)
export {
  getCrmSettings,
  updateCrmSettings,
  serializeCrmSettings,
  isLeadScoringEnabled,
  DEFAULT_PIPELINE_STAGES,
  DEFAULT_LOST_REASONS,
} from './settings-crm'
export type { CrmSettingsRow, UpdateCrmSettingsInput, PipelineStage } from './settings-crm'

// wave-15: inventory settings
export {
  getInventorySettings,
  updateInventorySettings,
  listInventoryLocations,
  createInventoryLocation,
  updateInventoryLocation,
  deleteInventoryLocation,
  InventoryLocationConflictError,
} from './settings-inventory'
export type {
  InventorySettingsObject,
  UpdateInventorySettingsInput,
  InventoryLocationObject,
  CreateInventoryLocationInput,
  UpdateInventoryLocationInput,
} from './settings-inventory'

// wave-15: scheduled-reports
export {
  listReportSchedules,
  getReportSchedule,
  getReportScheduleById,
  createReportSchedule,
  deleteReportSchedule,
  listDueSchedules,
  touchScheduleRun,
  deactivateSchedule,
  updateReportSchedule,
} from './report-schedules'
export type { ReportRecipient, CreateReportScheduleInput, UpdateReportScheduleInput, ReportScheduleRow } from './report-schedules'

// wave-15: bituach-leumi (spec 175)
export {
  getNiiReportAggregates,
  listNiiAdvances,
  getNiiAdvance,
  createNiiAdvance,
  updateNiiAdvance,
  deleteNiiAdvance,
} from './nii-advances'
export type { NiiReportAggregates } from './nii-advances'

// wave-15: accountant-export (spec 2026-06-01-accountant-export)
export {
  coaAccounts,
  coaMappings,
  accountantExportJobs,
  listCoaAccounts,
  upsertCoaAccounts,
  listCoaMappings,
  upsertCoaMappings,
  createAccountantExportJob,
  getAccountantExportJob,
  listAccountantExportJobs,
  setAccountantExportJobDone,
  setAccountantExportJobError,
  updateAccountantExportJobDownloadExpiry,
} from './accountant-export'
export type {
  CoaAccountRow,
  NewCoaAccount,
  CoaMappingRow,
  NewCoaMapping,
  AccountantExportJobRow,
  NewAccountantExportJob,
} from './accountant-export'

// wave-16: customer-statement (spec 183)
export { buildCustomerStatement, getCustomerBillingEmail } from './customer-statement'
export type { BuildStatementInput } from './customer-statement'
export { computeStatementAging } from './statement-aging'
export type { OpenInvoiceForAging } from './statement-aging'
