Skip to content

Open-source personal finance manager. Self-hosted, privacy-first.

84.7 KB
Raw Blame
import axios from 'axios'
import type { AxiosResponse } from 'axios'
import { markDataChanged } from '@/lib/data-changed'
import type { NumberFormat, DateFormat } from '@/lib/format'
import type {
  User,
  AdminUser,
  AdminUserList,
  Passkey,
  PasskeyOptionsResponse,
  AppSetting,
  Category,
  CategoryRuleUsage,
  CategoryUsage,
  CategoryGroup,
  BankConnection,
  ConnectionSettings,
  SyncResult,
  Account,
  AccountSummary,
  AccountRunningBalancePoint,
  Collection,
  CreditCardBill,
  LoanBalanceAdjustment,
  LoanBalanceUpdate,
  LoanSchedule,
  DescriptionSuggestion,
  Transaction,
  Payee,
  PayeeSummary,
  DeductionKind,
  InstallmentInput,
  Invoice,
  InvoiceDirection,
  InvoiceDocumentPayload,
  InvoiceFacets,
  InvoiceSchedule,
  InvoiceScheduleEndReason,
  InvoiceScheduleEndType,
  InvoiceScheduleFrequency,
  InvoiceSchedulePeriod,
  InvoiceScheduleStatus,
  InvoiceScheduleSummary,
  Product,
  ProductFieldSpec,
  ProductKind,
  PriceBilling,
  InvoiceLineInput,
  InvoiceShareLink,
  IssuerProfile,
  IssuerTaxId,
  InvoiceSettings,
  InvoiceSummary,
  RecurringTransaction,
  ProjectedTransaction,
  TransactionCalendarResponse,
  Budget,
  BudgetVsActual,
  BudgetSuggestionResponse,
  Rule,
  RuleAction,
  RuleConditionNode,
  RuleExportPayload,
  RuleImportResponse,
  RulePreviewResponse,
  ImportLog,
  ImportPreviewTransaction,
  FailedRow,
  PayeeTaxId,
  TaxIdKindOption,
  Workspace,
  WorkspaceKind,
  WorkspaceMember,
  WorkspaceRole,
  Asset,
  AssetGroup,
  AssetImportPreview,
  AssetImportResult,
  AssetOrderImport,
  AssetTransaction,
  AssetValue,
  MarketSymbolMatch,
  MarketSymbolQuote,
  Attachment,
  Goal,
  GoalSummary,
  DashboardSummary,
  SpendingByCategory,
  MonthlyTrend,
  BalanceHistory,
  PaginatedTransactions,
  ReportResponse,
  Group,
  GroupKind,
  GroupMember,
  GroupSettlement,
  GroupBalances,
  GroupSummary,
  TransactionSplitsInput,
  TransactionEditPayload,
  InstallmentSeriesInput,
  TransactionApplyScope,
  InvoiceAttachment,
  ReconciliationNode,
  ReconciliationPolicyFile,
  ReconciliationRule,
  ReconciliationRuleDraft,
  ReconciliationRulePatch,
  ReconciliationSuggestion,
  ReconciliationHistoryEvent,
} from '@/types'

const api = axios.create({
  baseURL: '/api',
})
export { api }

// Storage key for the currently-selected workspace ID. Lives in
// localStorage so reloads + new tabs stay on the same workspace until
// the user picks another one.
export const WORKSPACE_STORAGE_KEY = 'workspace_id'

// Add auth token + active workspace header to requests
api.interceptors.request.use((config) => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  const workspaceId = localStorage.getItem(WORKSPACE_STORAGE_KEY)
  if (workspaceId) {
    config.headers['X-Workspace-Id'] = workspaceId
  }
  return config
})

// Handle auth errors
api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

declare module 'axios' {
  interface AxiosRequestConfig {
    /** Set on POSTs that only read (previews, sign-in, tokens, tests) so
     * they do not tell other tabs that data changed. */
    skipDataChanged?: boolean
  }
}

/** Request config for a POST that changes nothing on the server. */
const readOnly = { skipDataChanged: true } as const

// A successful mutation here changes data that other tabs may be showing.
// The bump fires the `storage` event in those tabs, where
// `useCrossTabRefresh` turns it into a cache invalidation (issue #763).
// Read-only POSTs opt out: a preview query re-run by that invalidation would
// otherwise bump again and make two open tabs refresh each other forever.
api.interceptors.response.use(
  (response: AxiosResponse) => {
    const method = (response.config.method ?? 'get').toLowerCase()
    if (method !== 'get' && !response.config.skipDataChanged) markDataChanged()
    return response
  },
  (error: unknown) => Promise.reject(error)
)

// Workspaces
export const workspaces = {
  list: async (): Promise<Workspace[]> => {
    const { data } = await api.get('/workspaces')
    return data
  },
  current: async (): Promise<Workspace> => {
    const { data } = await api.get('/workspaces/current')
    return data
  },
  create: async (payload: {
    name: string
    kind?: WorkspaceKind
    default_currency?: string
    locale?: string
    tax_jurisdiction?: string | null
    icon?: string
    color?: string
    self_membership?: boolean
  }): Promise<Workspace> => {
    const { data } = await api.post('/workspaces', payload)
    return data
  },
  // `kind` is absent on purpose: it is fixed when the workspace is created.
  update: async (
    id: string,
    payload: Partial<
      Pick<Workspace, 'name' | 'icon' | 'color' | 'default_currency' | 'locale'>
    > & { tax_jurisdiction?: string | null; timezone?: string | null },
  ): Promise<Workspace> => {
    const { data } = await api.patch(`/workspaces/${id}`, payload)
    return data
  },
  listMembers: async (id: string): Promise<WorkspaceMember[]> => {
    const { data } = await api.get(`/workspaces/${id}/members`)
    return data
  },
  invite: async (id: string, payload: { email: string; role?: WorkspaceRole; password?: string }): Promise<WorkspaceMember> => {
    const { data } = await api.post(`/workspaces/${id}/members`, payload)
    return data
  },
  changeRole: async (id: string, memberUserId: string, role: WorkspaceRole): Promise<WorkspaceMember> => {
    const { data } = await api.patch(`/workspaces/${id}/members/${memberUserId}`, { role })
    return data
  },
  removeMember: async (id: string, memberUserId: string): Promise<void> => {
    await api.delete(`/workspaces/${id}/members/${memberUserId}`)
  },
  stats: async (id: string): Promise<{ members: number; accounts: number; transactions: number }> => {
    const { data } = await api.get(`/workspaces/${id}/stats`)
    return data
  },
  archive: async (id: string): Promise<Workspace> => {
    const { data } = await api.post(`/workspaces/${id}/archive`)
    return data
  },
}

// Setup
export const setup = {
  status: async (): Promise<{ has_users: boolean }> => {
    const { data } = await api.get('/setup/status')
    return data
  },
  createAdmin: async (email: string, password: string, currency = 'USD', name = '', language = 'en'): Promise<{ access_token: string }> => {
    const { data } = await api.post('/setup/create-admin', { email, password, currency, name, language })
    return data
  },
}

// Auth
export const auth = {
  login: async (email: string, password: string) => {
    const formData = new URLSearchParams()
    formData.append('username', email)
    formData.append('password', password)
    const { data } = await api.post('/auth/login', formData, {
      ...readOnly,
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    })
    return data
  },
  register: async (email: string, password: string, preferences?: Record<string, string>) => {
    const { data } = await api.post('/auth/register', { email, password, preferences })
    return data
  },
  me: async (): Promise<User> => {
    const { data } = await api.get('/users/me')
    return data
  },
  updateMe: async (updates: Partial<User>): Promise<User> => {
    const { data } = await api.patch('/users/me', updates)
    return data
  },
  changePassword: async (password: string): Promise<User> => {
    const { data } = await api.patch('/users/me', { password })
    return data
  },
  setup2fa: async (): Promise<{ secret: string; otpauth_uri: string }> => {
    const { data } = await api.post('/auth/2fa/setup')
    return data
  },
  enable2fa: async (code: string): Promise<void> => {
    await api.post('/auth/2fa/enable', { code })
  },
  disable2fa: async (password: string, code: string): Promise<void> => {
    await api.post('/auth/2fa/disable', { password, code })
  },
  verify2fa: async (tempToken: string, code: string): Promise<{ access_token: string; token_type: string }> => {
    const { data } = await api.post('/auth/2fa/verify', { temp_token: tempToken, code }, readOnly)
    return data
  },
  listPasskeys: async (): Promise<Passkey[]> => {
    const { data } = await api.get('/auth/passkeys')
    return data
  },
  registerPasskeyOptions: async (name: string): Promise<PasskeyOptionsResponse> => {
    const { data } = await api.post('/auth/passkeys/register/options', { name })
    return data
  },
  verifyPasskeyRegistration: async (
    challengeId: string,
    name: string,
    credential: Record<string, unknown>,
  ): Promise<Passkey> => {
    const { data } = await api.post('/auth/passkeys/register/verify', {
      challenge_id: challengeId,
      name,
      credential,
    })
    return data
  },
  deletePasskey: async (id: string): Promise<void> => {
    await api.delete(`/auth/passkeys/${id}`)
  },
  passkeyAuthenticationOptions: async (email?: string): Promise<PasskeyOptionsResponse> => {
    const { data } = await api.post('/auth/passkeys/authenticate/options', { email }, readOnly)
    return data
  },
  verifyPasskeyAuthentication: async (
    challengeId: string,
    credential: Record<string, unknown>,
  ): Promise<{ access_token: string; token_type: string }> => {
    const { data } = await api.post('/auth/passkeys/authenticate/verify', {
      challenge_id: challengeId,
      credential,
    }, readOnly)
    return data
  },
  passkeySecondFactorOptions: async (tempToken: string): Promise<PasskeyOptionsResponse> => {
    const { data } = await api.post('/auth/passkeys/2fa/options', { temp_token: tempToken }, readOnly)
    return data
  },
  verifyPasskeySecondFactor: async (
    tempToken: string,
    challengeId: string,
    credential: Record<string, unknown>,
  ): Promise<{ access_token: string; token_type: string }> => {
    const { data } = await api.post('/auth/passkeys/2fa/verify', {
      temp_token: tempToken,
      challenge_id: challengeId,
      credential,
    }, readOnly)
    return data
  },
  oidcConfig: async (): Promise<{ enabled: boolean; provider_name: string; local_auth_enabled: boolean }> => {
    // The login card blocks on this call while it decides which sign-in
    // methods to offer, so a hung request must fail fast and let the caller
    // fall back instead of leaving the page stuck on its loading state.
    const { data } = await api.get('/auth/oidc/config', { timeout: 5000 })
    return data
  },
}

// Categories
export const categories = {
  list: async (): Promise<Category[]> => {
    const { data } = await api.get('/categories')
    return data
  },
  listIncludingHidden: async (): Promise<Category[]> => {
    const { data } = await api.get('/categories', { params: { include_hidden: true } })
    return data
  },
  create: async (category: Partial<Category>): Promise<Category> => {
    const { data } = await api.post('/categories', category)
    return data
  },
  update: async (
    id: string,
    category: Partial<Category>,
    options?: { deactivateRules?: boolean },
  ): Promise<Category> => {
    const { data } = await api.patch(`/categories/${id}`, category, {
      params: options?.deactivateRules ? { deactivate_rules: true } : undefined,
    })
    return data
  },
  ruleUsage: async (id: string): Promise<CategoryRuleUsage> => {
    const { data } = await api.get(`/categories/${id}/rule-usage`)
    return data
  },
  usage: async (id: string): Promise<CategoryUsage> => {
    const { data } = await api.get(`/categories/${id}/usage`)
    return data
  },
  delete: async (id: string, transferToId?: string): Promise<void> => {
    await api.delete(`/categories/${id}`, {
      params: transferToId ? { transfer_to_category_id: transferToId } : undefined,
    })
  },
}

// Category Groups
export const categoryGroups = {
  list: async (): Promise<CategoryGroup[]> => {
    const { data } = await api.get('/category-groups')
    return data
  },
  listIncludingHidden: async (): Promise<CategoryGroup[]> => {
    const { data } = await api.get('/category-groups', { params: { include_hidden: true } })
    return data
  },
  create: async (group: Partial<CategoryGroup>): Promise<CategoryGroup> => {
    const { data } = await api.post('/category-groups', group)
    return data
  },
  update: async (id: string, group: Partial<CategoryGroup>): Promise<CategoryGroup> => {
    const { data } = await api.patch(`/category-groups/${id}`, group)
    return data
  },
  delete: async (id: string): Promise<void> => {
    await api.delete(`/category-groups/${id}`)
  },
}

// Bank Connections
export const connections = {
  list: async (): Promise<BankConnection[]> => {
    const { data } = await api.get('/connections')
    return data
  },
  getProviders: async (): Promise<{ name: string; display_name: string; description: string; flow_type: string; configured: boolean; requires_institution_select?: boolean; supports_asset_sync?: boolean }[]> => {
    const { data } = await api.get('/connections/providers')
    return data.providers
  },
  getConnectToken: async (provider = 'pluggy'): Promise<string> => {
    const { data } = await api.post('/connections/connect-token', { provider }, readOnly)
    return data.access_token
  },
  getOAuthUrl: async (provider: string, flow_params?: Record<string, unknown>): Promise<string> => {
    const { data } = await api.post('/connections/oauth/url', { provider, flow_params }, readOnly)
    return data.url
  },
  listInstitutions: async (
    provider: string,
    country?: string,
  ): Promise<{
    countries: string[]
    institutions: {
      name: string
      display_name: string
      country: string
      logo?: string | null
      bic?: string | null
      psu_types: string[]
      max_consent_days?: number | null
      max_history_days?: number | null
    }[]
  }> => {
    const { data } = await api.get(`/connections/${provider}/institutions`, {
      params: country ? { country } : undefined,
    })
    return data
  },
  handleCallback: async (
    code: string,
    provider: string,
    state?: string,
    settings?: Pick<ConnectionSettings, 'sync_assets'>,
    reconnectConnectionId?: string,
  ): Promise<BankConnection> => {
    const { data } = await api.post('/connections/oauth/callback', {
      code,
      provider,
      state,
      reconnect_connection_id: reconnectConnectionId,
      ...settings,
    })
    return data
  },
  getReauthUrl: async (connectionId: string): Promise<string> => {
    const { data } = await api.post(`/connections/${connectionId}/oauth/reauth-url`, undefined, readOnly)
    return data.url
  },
  sync: async (id: string): Promise<SyncResult> => {
    const { data } = await api.post(`/connections/${id}/sync`)
    return data
  },
  getReconnectToken: async (connectionId: string): Promise<string> => {
    const { data } = await api.post(`/connections/${connectionId}/reconnect-token`, undefined, readOnly)
    return data.access_token
  },
  updateSettings: async (
    id: string,
    settings: Partial<ConnectionSettings> & { display_name?: string | null },
  ): Promise<BankConnection> => {
    const { data } = await api.patch(`/connections/${id}/settings`, settings)
    return data
  },
  delete: async (id: string): Promise<void> => {
    await api.delete(`/connections/${id}`)
  },
}

// Accounts
export const accounts = {
  list: async (includeClosed = false): Promise<Account[]> => {
    const { data } = await api.get('/accounts', { params: { include_closed: includeClosed } })
    return data
  },
  get: async (id: string): Promise<Account> => {
    const { data } = await api.get(`/accounts/${id}`)
    return data
  },
  create: async (account: {
    name: string
    type: string
    balance?: number
    balance_date?: string
    currency?: string
    secured_asset_id?: string | null
    credit_limit?: number | null
    statement_close_day?: number | null
    payment_due_day?: number | null
  }): Promise<Account> => {
    const { data } = await api.post('/accounts', account)
    return data
  },
  update: async (id: string, account: Partial<Account>): Promise<Account> => {
    const { data } = await api.patch(`/accounts/${id}`, account)
    return data
  },
  delete: async (id: string): Promise<void> => {
    await api.delete(`/accounts/${id}`)
  },
  summary: async (id: string, from?: string, to?: string, billId?: string, unbilledOnly?: boolean): Promise<AccountSummary> => {
    const { data } = await api.get(`/accounts/${id}/summary`, { params: { from, to, bill_id: billId, unbilled_only: unbilledOnly || undefined } })
    return data
  },
  balanceHistory: async (id: string, from?: string, to?: string): Promise<{ date: string; balance: number; balance_primary?: number; fx_fallback?: boolean }[]> => {
    const { data } = await api.get(`/accounts/${id}/balance-history`, { params: { from, to } })
    return data
  },
  runningBalance: async (id: string, from?: string, to?: string): Promise<AccountRunningBalancePoint[]> => {
    const { data } = await api.get(`/accounts/${id}/running-balance`, { params: { from, to } })
    return data
  },
  loanSchedule: async (id: string): Promise<LoanSchedule> => {
    const { data } = await api.get(`/accounts/${id}/loan-schedule`)
    return data
  },
  adjustLoanBalance: async (id: string, body: LoanBalanceUpdate): Promise<LoanBalanceAdjustment> => {
    const { data } = await api.post(`/accounts/${id}/loan-balance`, body)
    return data
  },
  bills: async (id: string, limit = 24): Promise<CreditCardBill[]> => {
    const { data } = await api.get(`/accounts/${id}/bills`, { params: { limit } })
    return data
  },
  close: async (id: string): Promise<Account> => {
    const { data } = await api.post(`/accounts/${id}/close`)
    return data
  },
  reopen: async (id: string): Promise<Account> => {
    const { data } = await api.post(`/accounts/${id}/reopen`)
    return data
  },
}

export interface MortgagePaymentAllocation {
  loan_account_id: string
  loan_name: string
  principal_amount: number
  interest_amount: number
  payment_amount: number
  principal_percentage: number
  interest_percentage: number
  historical: boolean
  bank_managed: boolean
}

export const mortgagePayments = {
  get: async (paymentId: string): Promise<{
    payment_transaction_id: string
    payment_amount: number
    currency: string
    payment_account_name: string
    allocations: MortgagePaymentAllocation[]
    principal_total: number
    interest_total: number
    principal_percentage: number
    interest_percentage: number
  }> => {
    const { data } = await api.get(`/mortgage-payments/${paymentId}`)
    return data
  },
  replace: async (
    paymentId: string,
    allocations: {
      loan_account_id: string
      principal_amount: number
      interest_amount: number
    }[],
  ) => {
    const { data } = await api.put(`/mortgage-payments/${paymentId}`, { allocations })
    return data
  },
  remove: async (paymentId: string): Promise<void> => {
    await api.delete(`/mortgage-payments/${paymentId}`)
  },
}

// Transactions
export const transactions = {
  list: async (params?: {
    account_id?: string
    account_ids?: string[]
    category_id?: string
    category_ids?: string[]
    payee_id?: string
    uncategorized?: boolean
    type?: string
    status?: string
    from?: string
    to?: string
    bill_id?: string
    group_id?: string
    unbilled_only?: boolean
    q?: string
    page?: number
    limit?: number
    include_opening_balance?: boolean
    include_running_balance?: boolean
    exclude_transfers?: boolean
    user_pnl_only?: boolean
    exclude_ignored?: boolean
    tags?: string[]
    min_amount?: number
    max_amount?: number
    sort_by?: string
    sort_dir?: 'asc' | 'desc'
  }): Promise<PaginatedTransactions> => {
    const { data } = await api.get('/transactions', {
      params,
      paramsSerializer: { indexes: null },
    })
    return data
  },
  calendar: async (params?: {
    month?: string
    account_id?: string
    account_ids?: string[]
  }): Promise<TransactionCalendarResponse> => {
    const { data } = await api.get('/transactions/calendar', {
      params,
      paramsSerializer: { indexes: null },
    })
    return data
  },
  get: async (id: string): Promise<Transaction> => {
    const { data } = await api.get(`/transactions/${id}`)
    return data
  },
  descriptionSuggestions: async (q: string, limit = 8): Promise<DescriptionSuggestion[]> => {
    const { data } = await api.get('/transactions/description-suggestions', { params: { q, limit } })
    return data
  },
  create: async (transaction: TransactionEditPayload): Promise<Transaction> => {
    const { data } = await api.post('/transactions', transaction)
    return data
  },
  createInstallments: async (payload: InstallmentSeriesInput): Promise<Transaction[]> => {
    const { data } = await api.post('/transactions/installments', payload)
    return data
  },
  update: async (
    id: string,
    transaction: TransactionEditPayload & {
      apply_to_transfer_pair?: boolean
      apply_to?: TransactionApplyScope
    },
  ): Promise<Transaction> => {
    const { data } = await api.patch(`/transactions/${id}`, transaction)
    return data
  },
  delete: async (id: string, applyTo: TransactionApplyScope = 'this'): Promise<void> => {
    await api.delete(`/transactions/${id}`, { params: { apply_to: applyTo } })
  },
  toggleIgnore: async (id: string): Promise<Transaction> => {
    const { data } = await api.patch(`/transactions/${id}/ignore`)
    return data
  },
  unlinkRecurring: async (id: string): Promise<Transaction> => {
    const { data } = await api.patch(`/transactions/${id}/unlink-recurring`)
    return data
  },
  postToday: async (id: string): Promise<Transaction> => {
    const { data } = await api.post(`/transactions/${id}/post-today`)
    return data
  },
  createTransfer: async (transfer: {
    from_account_id: string
    to_account_id: string
    amount: number
    date: string
    description: string
    notes?: string
    destination_amount?: number
  }): Promise<{ debit: Transaction; credit: Transaction; transfer_pair_id: string }> => {
    const { data } = await api.post('/transactions/transfer', transfer)
    return data
  },
  bulkCategorize: async (transactionIds: string[], categoryId: string | null): Promise<{ updated: number }> => {
    const { data } = await api.patch('/transactions/bulk-categorize', {
      transaction_ids: transactionIds,
      category_id: categoryId,
    })
    return data
  },
  bulkAddTags: async (transactionIds: string[], tags: string[]): Promise<{ updated: number }> => {
    const { data } = await api.patch('/transactions/bulk-add-tags', {
      transaction_ids: transactionIds,
      tags,
    })
    return data
  },
  bulkRemoveTags: async (transactionIds: string[], tags: string[]): Promise<{ updated: number }> => {
    const { data } = await api.patch('/transactions/bulk-remove-tags', {
      transaction_ids: transactionIds,
      tags,
    })
    return data
  },
  bulkAddToGroup: async (
    transactionIds: string[],
    groupId: string,
    options?: {
      share_type?: 'equal' | 'percent'
      member_splits?: { group_member_id: string; share_pct?: number }[]
    },
  ): Promise<{ updated: number; skipped: number }> => {
    const { data } = await api.patch('/transactions/bulk-add-to-group', {
      transaction_ids: transactionIds,
      group_id: groupId,
      ...(options?.share_type ? { share_type: options.share_type } : {}),
      ...(options?.member_splits ? { member_splits: options.member_splits } : {}),
    })
    return data
  },
  bulkDelete: async (transactionIds: string[]): Promise<{ deleted: number }> => {
    const { data } = await api.post('/transactions/bulk-delete', {
      transaction_ids: transactionIds,
    })
    return data
  },
  linkTransfer: async (transactionIds: string[]): Promise<{ debit: Transaction; credit: Transaction; transfer_pair_id: string }> => {
    const { data } = await api.post('/transactions/link-transfer', {
      transaction_ids: transactionIds,
    })
    return data
  },
  createTransferCounterpart: async (
    transactionId: string,
    toAccountId: string,
  ): Promise<{ debit: Transaction; credit: Transaction; transfer_pair_id: string }> => {
    const { data } = await api.post(`/transactions/${transactionId}/create-counterpart`, {
      to_account_id: toAccountId,
    })
    return data
  },
  transferCandidates: async (transactionId: string, params?: { limit?: number; window_days?: number }): Promise<Transaction[]> => {
    const { data } = await api.get(`/transactions/${transactionId}/transfer-candidates`, { params })
    return data
  },
  transferPair: async (transactionId: string): Promise<Transaction | null> => {
    const { data } = await api.get(`/transactions/${transactionId}/transfer-pair`)
    return data
  },
  unlinkTransfer: async (pairId: string): Promise<void> => {
    await api.delete(`/connections/transfers/${pairId}`)
  },
  previewImport: async (file: File, options?: {
    date_format?: string
    flip_amount?: boolean
    inflow_column?: string
    outflow_column?: string
    column_mapping?: Record<string, string>
  }): Promise<{ transactions: ImportPreviewTransaction[]; detected_format: string; csv_columns?: string[]; parse_error?: string | null; failed_rows?: FailedRow[] }> => {
    const formData = new FormData()
    formData.append('file', file)
    if (options?.date_format) formData.append('date_format', options.date_format)
    if (options?.flip_amount) formData.append('flip_amount', 'true')
    if (options?.inflow_column) formData.append('inflow_column', options.inflow_column)
    if (options?.outflow_column) formData.append('outflow_column', options.outflow_column)
    if (options?.column_mapping && Object.keys(options.column_mapping).length > 0) {
      formData.append('column_mapping', JSON.stringify(options.column_mapping))
    }
    const { data } = await api.post('/transactions/import/preview', formData, readOnly)
    return data
  },
  import: async (
    account_id: string,
    transactions: ImportPreviewTransaction[],
    filename: string,
    detected_format: string,
    options?: { detect_duplicates?: boolean },
  ): Promise<{ imported: number; skipped: number; excluded: number; import_log_id: string }> => {
    const payload: {
      account_id: string
      transactions: ImportPreviewTransaction[]
      filename: string
      detected_format: string
      detect_duplicates?: boolean
    } = { account_id, transactions, filename, detected_format }

    if (typeof options?.detect_duplicates === 'boolean') {
      payload.detect_duplicates = options.detect_duplicates
    }

    const { data } = await api.post('/transactions/import', payload)
    return data
  },
  export: async (params?: {
    account_id?: string
    account_ids?: string[]
    category_id?: string
    category_ids?: string[]
    payee_id?: string
    uncategorized?: boolean
    type?: string
    status?: string
    from?: string
    to?: string
    q?: string
    tags?: string[]
    exclude_ignored?: boolean
    transaction_ids?: string[]
  }): Promise<void> => {
    const { data } = await api.get('/transactions/export', {
      params,
      responseType: 'blob',
      paramsSerializer: { indexes: null },
    })
    const blob = new Blob([data], { type: 'text/csv;charset=utf-8;' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `transactions-${new Date().toISOString().slice(0, 10)}.csv`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
  },
  attachments: {
    list: async (transactionId: string): Promise<Attachment[]> => {
      const { data } = await api.get(`/transactions/${transactionId}/attachments`)
      return data
    },
    upload: async (transactionId: string, file: File): Promise<Attachment> => {
      const formData = new FormData()
      formData.append('file', file)
      const { data } = await api.post(`/transactions/${transactionId}/attachments`, formData)
      return data
    },
    downloadUrl: async (transactionId: string, attachmentId: string): Promise<string> => {
      const { data } = await api.get(`/transactions/${transactionId}/attachments/${attachmentId}`, {
        responseType: 'blob',
      })
      return URL.createObjectURL(data)
    },
    rename: async (transactionId: string, attachmentId: string, filename: string): Promise<Attachment> => {
      const { data } = await api.patch(`/transactions/${transactionId}/attachments/${attachmentId}`, { filename })
      return data
    },
    delete: async (transactionId: string, attachmentId: string): Promise<void> => {
      await api.delete(`/transactions/${transactionId}/attachments/${attachmentId}`)
    },
  },
}

// Payees
/** Jurisdiction metadata. Labels, masks and ordering come from the server so
 *  the browser cannot disagree with it about what a document looks like. */
export const fiscal = {
  jurisdictions: async (): Promise<string[]> => {
    const { data } = await api.get('/fiscal/jurisdictions')
    return data.jurisdictions
  },
  taxIdKinds: async (): Promise<{
    jurisdiction: string | null
    kinds: TaxIdKindOption[]
    /** Country to documents, for grouping and searching the picker by country. */
    jurisdictions: { code: string; kinds: string[] }[]
  }> => {
    const { data } = await api.get('/fiscal/tax-id-kinds')
    return data
  },
  /** Fiscal references the workspace's jurisdiction suggests on a product. */
  productFields: async (): Promise<{ jurisdiction: string | null; fields: ProductFieldSpec[] }> => {
    const { data } = await api.get('/fiscal/product-fields')
    return data
  },
}

export interface PayeeWritePayload {
  name?: string
  /** Null clears the legal nature. `source` is never writable. */
  type?: 'person' | 'company' | null
  notes?: string
  email?: string | null
  phone?: string | null
  address?: string | null
  website?: string | null
  is_favorite?: boolean
  /** Replaces the whole set. Omit to leave documents untouched. */
  tax_ids?: PayeeTaxId[]
}

export interface PricePayload {
  currency: string
  unit_price: string
  tax_rate?: string | null
  billing?: PriceBilling
  interval?: InvoiceScheduleFrequency | null
  nickname?: string | null
  lookup_key?: string | null
}

export interface ProductPayload {
  name?: string
  description?: string | null
  kind?: ProductKind
  unit?: string | null
  active?: boolean
  fiscal_refs?: Record<string, string> | null
  prices?: PricePayload[]
}

/** The catalog: what the workspace sells. Gated like invoices. */
export const products = {
  list: async (params?: { active?: boolean | null; kind?: ProductKind; q?: string }): Promise<Product[]> => {
    const { data } = await api.get('/products', {
      params: {
        ...(params?.active === undefined ? {} : { active: params.active }),
        ...(params?.kind ? { kind: params.kind } : {}),
        ...(params?.q ? { q: params.q } : {}),
      },
    })
    return data
  },
  get: async (id: string): Promise<Product> => {
    const { data } = await api.get(`/products/${id}`)
    return data
  },
  create: async (payload: ProductPayload): Promise<Product> => {
    const { data } = await api.post('/products', payload)
    return data
  },
  update: async (id: string, payload: ProductPayload): Promise<Product> => {
    const { data } = await api.patch(`/products/${id}`, payload)
    return data
  },
  remove: async (id: string): Promise<void> => {
    await api.delete(`/products/${id}`)
  },
  addPrice: async (id: string, payload: PricePayload): Promise<Product> => {
    const { data } = await api.post(`/products/${id}/prices`, payload)
    return data
  },
  updatePrice: async (id: string, priceId: string, payload: Partial<PricePayload> & { active?: boolean }): Promise<Product> => {
    const { data } = await api.patch(`/products/${id}/prices/${priceId}`, payload)
    return data
  },
  removePrice: async (id: string, priceId: string): Promise<Product> => {
    const { data } = await api.delete(`/products/${id}/prices/${priceId}`)
    return data
  },
}

export const payees = {
  list: async (params?: { q?: string; type?: string; is_favorite?: boolean } | Record<string, unknown>): Promise<Payee[]> => {
    const cleanParams = params && !('queryKey' in params) ? params : undefined
    const { data } = await api.get('/payees', { params: cleanParams })
    return data
  },
  get: async (id: string): Promise<Payee> => {
    const { data } = await api.get(`/payees/${id}`)
    return data
  },
  summary: async (id: string, from?: string, to?: string): Promise<PayeeSummary> => {
    const { data } = await api.get(`/payees/${id}/summary`, { params: { from, to } })
    return data
  },
  create: async (payee: PayeeWritePayload & { name: string }): Promise<Payee> => {
    const { data } = await api.post('/payees', payee)
    return data
  },
  update: async (id: string, payee: PayeeWritePayload): Promise<Payee> => {
    const { data } = await api.patch(`/payees/${id}`, payee)
    return data
  },
  delete: async (id: string): Promise<void> => {
    await api.delete(`/payees/${id}`)
  },
  merge: async (targetId: string, sourceIds: string[]): Promise<{ merged: number; transactions_reassigned: number }> => {
    const { data } = await api.post('/payees/merge', { target_id: targetId, source_ids: sourceIds })
    return data
  },
  bulkDelete: async (ids: string[]): Promise<{ deleted: number }> => {
    const { data } = await api.post('/payees/bulk-delete', { ids })
    return data
  },
}

// Groups (split transactions)
export interface GroupCreatePayload {
  name: string
  kind?: GroupKind
  default_currency?: string
  icon?: string
  color?: string
  notes?: string | null
}

export interface GroupMemberPayload {
  name: string
  linked_user_id?: string | null
  email?: string | null
  is_self?: boolean
}

export interface GroupSettlementPayload {
  from_member_id: string
  to_member_id: string
  amount: number
  currency: string
  date: string
  transaction_id?: string | null
  notes?: string | null
  // When provided, the backend creates a debit transaction on this
  // account and links it via transaction_id. Mutually exclusive with
  // passing transaction_id directly.
  account_id?: string | null
  description?: string | null
}

export const groups = {
  list: async (includeArchived = false, filters: { q?: string; status?: 'active' | 'archived' | 'all' } = {}): Promise<Group[]> => {
    const { data } = await api.get('/groups', { params: { include_archived: includeArchived, ...filters } })
    return data
  },
  get: async (id: string): Promise<Group> => {
    const { data } = await api.get(`/groups/${id}`)
    return data
  },
  create: async (payload: GroupCreatePayload): Promise<Group> => {
    const { data } = await api.post('/groups', payload)
    return data
  },
  update: async (id: string, payload: Partial<GroupCreatePayload> & { is_archived?: boolean }): Promise<Group> => {
    const { data } = await api.patch(`/groups/${id}`, payload)
    return data
  },
  delete: async (id: string): Promise<void> => {
    await api.delete(`/groups/${id}`)
  },
  members: {
    list: async (groupId: string): Promise<GroupMember[]> => {
      const { data } = await api.get(`/groups/${groupId}/members`)
      return data
    },
    create: async (groupId: string, payload: GroupMemberPayload): Promise<GroupMember> => {
      const { data } = await api.post(`/groups/${groupId}/members`, payload)
      return data
    },
    update: async (groupId: string, memberId: string, payload: Partial<GroupMemberPayload>): Promise<GroupMember> => {
      const { data } = await api.patch(`/groups/${groupId}/members/${memberId}`, payload)
      return data
    },
    delete: async (groupId: string, memberId: string): Promise<void> => {
      await api.delete(`/groups/${groupId}/members/${memberId}`)
    },
  },
  settlements: {
    list: async (groupId: string): Promise<GroupSettlement[]> => {
      const { data } = await api.get(`/groups/${groupId}/settlements`)
      return data
    },
    create: async (groupId: string, payload: GroupSettlementPayload): Promise<GroupSettlement> => {
      const { data } = await api.post(`/groups/${groupId}/settlements`, payload)
      return data
    },
    update: async (groupId: string, settlementId: string, payload: Partial<GroupSettlementPayload>): Promise<GroupSettlement> => {
      const { data } = await api.patch(`/groups/${groupId}/settlements/${settlementId}`, payload)
      return data
    },
    delete: async (groupId: string, settlementId: string): Promise<void> => {
      await api.delete(`/groups/${groupId}/settlements/${settlementId}`)
    },
  },
  balances: async (groupId: string): Promise<GroupBalances> => {
    const { data } = await api.get(`/groups/${groupId}/balances`)
    return data
  },
  summary: async (groupId: string): Promise<GroupSummary> => {
    const { data } = await api.get(`/groups/${groupId}/summary`)
    return data
  },
  transactions: async (groupId: string, limit = 20): Promise<Transaction[]> => {
    const { data } = await api.get(`/groups/${groupId}/transactions`, {
      params: { limit },
    })
    return data
  },
}

// Helper re-export so transaction-creation forms have a typed entry point.
export type { TransactionSplitsInput }

// User lookup: exact-match resolution for linking group members to
// existing Securo users. Returns null on miss (404).
export interface UserLookupResult {
  id: string
  email: string
}

export const users = {
  lookupByEmail: async (email: string): Promise<UserLookupResult | null> => {
    try {
      const { data } = await api.get('/users/lookup', { params: { email } })
      return data
    } catch (err: unknown) {
      const status = (err as { response?: { status?: number } })?.response?.status
      if (status === 404) return null
      throw err
    }
  },
  directory: async (): Promise<UserLookupResult[]> => {
    const { data } = await api.get('/users/directory')
    return data
  },
}


// Categorization Rules
export const rules = {
  list: async (): Promise<Rule[]> => {
    const { data } = await api.get('/rules')
    return data
  },
  create: async (rule: Omit<Rule, 'id' | 'user_id'>): Promise<Rule & { applied_count: number }> => {
    const { data } = await api.post('/rules', rule)
    return data
  },
  update: async (id: string, rule: Partial<Rule>): Promise<Rule & { applied_count: number }> => {
    const { data } = await api.patch(`/rules/${id}`, rule)
    return data
  },
  delete: async (id: string): Promise<void> => {
    await api.delete(`/rules/${id}`)
  },
  preview: async (draft: {
    conditions_op: 'and' | 'or'
    conditions: RuleConditionNode[]
    actions: RuleAction[]
    is_active?: boolean
    apply_to_existing?: boolean
    overwrite_existing_categories?: boolean
    /** One window of the matches: `limit` of them starting at `offset`,
     * newest first. The counts are exact whatever the window is. */
    limit?: number
    offset?: number
  }): Promise<RulePreviewResponse> => {
    const { data } = await api.post('/rules/preview', draft, readOnly)
    return data
  },
  applyAll: async (): Promise<{ applied: number }> => {
    const { data } = await api.post('/rules/apply-all')
    return data
  },
  exportFile: async (): Promise<void> => {
    const { data } = await api.get('/rules/export', { responseType: 'blob' })
    const blob = new Blob([data], { type: 'application/json;charset=utf-8;' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `securo-categorization-rules-${new Date().toISOString().slice(0, 10)}.json`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
  },
  importFile: async (payload: RuleExportPayload, overwrite = false): Promise<RuleImportResponse> => {
    const { data } = await api.post('/rules/import', { payload, overwrite })
    return data
  },
  packs: async (): Promise<{ code: string; name: string; flag: string; rule_count: number; installed: boolean }[]> => {
    const { data } = await api.get('/rules/packs')
    return data
  },
  installPack: async (
    packCode: string,
    createMissingCategories = false,
  ): Promise<{ installed: number; unresolved: number; categories_created: number }> => {
    const { data } = await api.post(`/rules/packs/${packCode}/install`, null, {
      params: { create_missing_categories: createMissingCategories },
    })
    return data
  },
}

// Recurring Transactions
// Reconciliation: the rules matching follows, and the matches it was
// not confident enough to make on its own.
export const reconciliation = {
  rules: async (): Promise<ReconciliationNode[]> => {
    const { data } = await api.get('/reconciliation/rules')
    return data
  },
  updateRule: async (
    node: string,
    id: string,
    patch: ReconciliationRulePatch,
  ): Promise<ReconciliationRule> => {
    const { data } = await api.patch(
      `/reconciliation/rules/${encodeURIComponent(node)}/${encodeURIComponent(id)}`,
      patch,
    )
    return data
  },
  /** Set the order rules are tried in. Names every rule in the set: the
   *  first match wins, so a half-implicit order rearranges itself the day
   *  a new default ships. */
  reorderRules: async (
    node: string,
    order: string[],
  ): Promise<ReconciliationRule[]> => {
    const { data } = await api.put(
      `/reconciliation/rules/${encodeURIComponent(node)}/order`,
      { order },
    )
    return data
  },
  createRule: async (rule: ReconciliationRuleDraft): Promise<ReconciliationRule> => {
    const { data } = await api.post('/reconciliation/rules', rule)
    return data
  },
  /** Get rid of a rule, whoever wrote it: ours included. What happens
   *  underneath differs (a rule of your own is a row and goes; one of
   *  ours ships in the image, so a tombstone records that this workspace
   *  does not run it) but that is our problem, not something to make a
   *  person learn. */
  deleteRule: async (node: string, id: string): Promise<void> => {
    await api.delete(
      `/reconciliation/rules/${encodeURIComponent(node)}/${encodeURIComponent(id)}`,
    )
  },
  /** Forget everything this workspace did to one of our rules (a moved
   *  threshold, a place in the order, a deletion), and go back to
   *  whatever we ship today. */
  resetRule: async (node: string, id: string): Promise<void> => {
    await api.post(
      `/reconciliation/rules/${encodeURIComponent(node)}/${encodeURIComponent(id)}/reset`,
    )
  },
  /** `node` narrows the file to one set. Each set is its own card with
   *  its own button, and a button under one heading that hands over
   *  another set's rules is a button that lies. */
  exportRules: async (node?: string): Promise<void> => {
    const { data } = await api.get('/reconciliation/rules/export', {
      responseType: 'blob',
      params: node ? { node } : undefined,
    })
    const blob = new Blob([data], { type: 'application/json;charset=utf-8;' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    // The set in the filename, so two exports do not overwrite each
    // other in the downloads folder on the same day.
    const set = node ? `-${node.split('.').pop()}` : ''
    a.download = `securo-reconciliation-rules${set}-${new Date().toISOString().slice(0, 10)}.json`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
  },
  /** Replaces rather than merges: order is the mechanism here, and there
   *  is no correct way to interleave two orderings. Hence `overwrite`. */
  importRules: async (
    payload: ReconciliationPolicyFile,
    overwrite = false,
    node?: string,
  ): Promise<{ imported: number; skipped: number }> => {
    const { data } = await api.post(
      '/reconciliation/rules/import',
      { payload, overwrite },
      { params: node ? { node } : undefined },
    )
    return data
  },
  /** What matching did, newest first. `expectationId` narrows it to
   *  everything that ever happened to one invoice. */
  history: async (
    expectationId?: string,
  ): Promise<ReconciliationHistoryEvent[]> => {
    const { data } = await api.get('/reconciliation/history', {
      params: expectationId ? { expectation_id: expectationId } : undefined,
    })
    return data
  },
  suggestions: async (): Promise<ReconciliationSuggestion[]> => {
    const { data } = await api.get('/reconciliation/suggestions')
    return data
  },
  accept: async (id: string): Promise<ReconciliationSuggestion> => {
    const { data } = await api.post(`/reconciliation/suggestions/${id}/accept`)
    return data
  },
  decline: async (id: string): Promise<ReconciliationSuggestion> => {
    const { data } = await api.post(`/reconciliation/suggestions/${id}/decline`)
    return data
  },
}

export const recurring = {
  list: async (): Promise<RecurringTransaction[]> => {
    const { data } = await api.get('/recurring-transactions')
    return data
  },
  create: async (rt: Partial<RecurringTransaction>): Promise<RecurringTransaction> => {
    const { data } = await api.post('/recurring-transactions', rt)
    return data
  },
  update: async (id: string, rt: Partial<RecurringTransaction>): Promise<RecurringTransaction> => {
    const { data } = await api.patch(`/recurring-transactions/${id}`, rt)
    return data
  },
  delete: async (id: string): Promise<void> => {
    await api.delete(`/recurring-transactions/${id}`)
  },
  generate: async (): Promise<{ generated: number }> => {
    const { data } = await api.post('/recurring-transactions/generate')
    return data
  },
}

// Budgets
export const budgets = {
  list: async (month?: string): Promise<Budget[]> => {
    const { data } = await api.get('/budgets', { params: { month } })
    return data
  },
  create: async (budget: { category_id: string; amount: number; month: string; is_recurring?: boolean }): Promise<Budget> => {
    const { data } = await api.post('/budgets', budget)
    return data
  },
  update: async (id: string, budget: { amount?: number }): Promise<Budget> => {
    const { data } = await api.patch(`/budgets/${id}`, budget)
    return data
  },
  delete: async (id: string): Promise<void> => {
    await api.delete(`/budgets/${id}`)
  },
  comparison: async (month?: string): Promise<BudgetVsActual[]> => {
    const { data } = await api.get('/budgets/comparison', { params: { month } })
    return data
  },
  suggestions: async (month: string, months: number): Promise<BudgetSuggestionResponse> => {
    const { data } = await api.get('/budgets/suggestions', { params: { month, months } })
    return data
  },
  createBatch: async (payload: {
    month: string
    is_recurring: boolean
    items: { category_id: string; amount: number }[]
  }): Promise<Budget[]> => {
    const { data } = await api.post('/budgets/batch', payload)
    return data
  },
}

// Goals
export const goals = {
  list: async (status?: string): Promise<Goal[]> => {
    const { data } = await api.get('/goals', { params: { status } })
    return data
  },
  get: async (id: string): Promise<Goal> => {
    const { data } = await api.get(`/goals/${id}`)
    return data
  },
  create: async (goal: Partial<Goal>): Promise<Goal> => {
    const { data } = await api.post('/goals', goal)
    return data
  },
  update: async (id: string, goal: Partial<Goal>): Promise<Goal> => {
    const { data } = await api.patch(`/goals/${id}`, goal)
    return data
  },
  delete: async (id: string): Promise<void> => {
    await api.delete(`/goals/${id}`)
  },
  summary: async (limit = 3): Promise<GoalSummary[]> => {
    const { data } = await api.get('/goals/summary', { params: { limit } })
    return data
  },
}

// Dashboard
// Repeated `account_ids=a&account_ids=b` (no [] brackets) so FastAPI's
// list[UUID] query param parses them. Only attached when a filter is active.
const acctIdsParam = (accountIds?: string[]) =>
  accountIds && accountIds.length > 0
    ? { params: { account_ids: accountIds }, paramsSerializer: { indexes: null as null } }
    : {}

export const dashboard = {
  summary: async (month?: string, balanceDate?: string, accountIds?: string[], assetGroupIds?: string[]): Promise<DashboardSummary> => {
    const hasFilter = (accountIds && accountIds.length > 0) || (assetGroupIds && assetGroupIds.length > 0)
    const { data } = await api.get('/dashboard/summary', {
      params: {
        month, balance_date: balanceDate,
        ...(accountIds && accountIds.length > 0 ? { account_ids: accountIds } : {}),
        ...(assetGroupIds && assetGroupIds.length > 0 ? { asset_group_ids: assetGroupIds } : {}),
      },
      ...(hasFilter ? { paramsSerializer: { indexes: null as null } } : {}),
    })
    return data
  },
  spendingByCategory: async (month?: string, accountIds?: string[]): Promise<SpendingByCategory[]> => {
    const extra = acctIdsParam(accountIds)
    const { data } = await api.get('/dashboard/spending-by-category', { params: { month, ...(extra.params ?? {}) }, ...(extra.paramsSerializer ? { paramsSerializer: extra.paramsSerializer } : {}) })
    return data
  },
  monthlyTrend: async (months = 6, accountIds?: string[]): Promise<MonthlyTrend[]> => {
    const extra = acctIdsParam(accountIds)
    const { data } = await api.get('/dashboard/monthly-trend', { params: { months, ...(extra.params ?? {}) }, ...(extra.paramsSerializer ? { paramsSerializer: extra.paramsSerializer } : {}) })
    return data
  },
  projectedTransactions: async (params?: { month?: string; account_id?: string; from?: string; to?: string }): Promise<ProjectedTransaction[]> => {
    const { data } = await api.get('/dashboard/projected-transactions', { params })
    return data
  },
  balanceHistory: async (
    month?: string,
    accountIds?: string[],
    comparisonMonths?: string[],
  ): Promise<BalanceHistory> => {
    const extra = acctIdsParam(accountIds)
    const { data } = await api.get('/dashboard/balance-history', {
      params: {
        month,
        ...(extra.params ?? {}),
        ...(comparisonMonths?.length ? { comparison_months: comparisonMonths } : {}),
      },
      paramsSerializer: { indexes: null },
    })
    return data
  },
  balanceHistoryMonths: async (accountIds?: string[]): Promise<string[]> => {
    const extra = acctIdsParam(accountIds)
    const { data } = await api.get('/dashboard/balance-history/months', {
      params: extra.params,
      ...(extra.paramsSerializer ? { paramsSerializer: extra.paramsSerializer } : {}),
    })
    return data
  },
}

// Assets
export const assets = {
  list: async (includeArchived = false): Promise<Asset[]> => {
    const { data } = await api.get('/assets', { params: { include_archived: includeArchived } })
    return data
  },
  get: async (id: string): Promise<Asset> => {
    const { data } = await api.get(`/assets/${id}`)
    return data
  },
  create: async (asset: Partial<Asset> & { name: string; type: string; current_value?: number }): Promise<Asset> => {
    const { data } = await api.post('/assets', asset)
    return data
  },
  update: async (id: string, asset: Partial<Asset>, opts?: { regenerateGrowth?: boolean }): Promise<Asset> => {
    const { data } = await api.patch(`/assets/${id}`, asset, {
      params: opts?.regenerateGrowth ? { regenerate_growth: true } : undefined,
    })
    return data
  },
  delete: async (id: string): Promise<void> => {
    await api.delete(`/assets/${id}`)
  },
  values: async (id: string): Promise<AssetValue[]> => {
    const { data } = await api.get(`/assets/${id}/values`)
    return data
  },
  valueTrend: async (id: string, months = 12): Promise<{ date: string; amount: number }[]> => {
    const { data } = await api.get(`/assets/${id}/value-trend`, { params: { months } })
    return data
  },
  addValue: async (id: string, value: { amount: number; date: string }): Promise<AssetValue> => {
    const { data } = await api.post(`/assets/${id}/values`, value)
    return data
  },
  deleteValue: async (valueId: string): Promise<void> => {
    await api.delete(`/assets/values/${valueId}`)
  },
  portfolioTrend: async (): Promise<{ assets: { id: string; name: string; type: string; group_id: string | null }[]; trend: Record<string, unknown>[]; total: number }> => {
    const { data } = await api.get('/assets/portfolio-trend')
    return data
  },
  marketSearch: async (q: string, limit = 15): Promise<MarketSymbolMatch[]> => {
    const { data } = await api.get('/assets/market/search', { params: { q, limit } })
    return data
  },
  marketQuote: async (symbol: string): Promise<MarketSymbolQuote> => {
    const { data } = await api.get('/assets/market/quote', { params: { symbol } })
    return data
  },
  refreshPrice: async (id: string): Promise<Asset> => {
    const { data } = await api.post(`/assets/${id}/refresh-price`)
    return data
  },
  // Transaction ledger (issue #235)
  transactions: async (id: string): Promise<AssetTransaction[]> => {
    const { data } = await api.get(`/assets/${id}/transactions`)
    return data
  },
  allTransactions: async (params?: { ticker?: string; kind?: 'buy' | 'sell' }): Promise<AssetTransaction[]> => {
    const { data } = await api.get('/assets/transactions', { params })
    return data
  },
  addTransaction: async (
    id: string,
    tx: { kind: 'buy' | 'sell'; quantity: number; price: number; fee?: number; date: string; notes?: string },
  ): Promise<Asset> => {
    const { data } = await api.post(`/assets/${id}/transactions`, tx)
    return data
  },
  updateTransaction: async (
    txId: string,
    tx: Partial<{ kind: 'buy' | 'sell'; quantity: number; price: number; fee: number; date: string; notes: string }>,
  ): Promise<Asset> => {
    const { data } = await api.patch(`/assets/transactions/${txId}`, tx)
    return data
  },
  deleteTransaction: async (txId: string): Promise<Asset> => {
    const { data } = await api.delete(`/assets/transactions/${txId}`)
    return data
  },
  buy: async (
    tx: { ticker: string; quantity: number; price: number; fee?: number; date: string; name?: string; group_id?: string | null; notes?: string },
  ): Promise<Asset> => {
    const { data } = await api.post('/assets/buy', tx)
    return data
  },
  previewImport: async (
    file: File,
    options?: { column_mapping?: Record<string, string>; date_format?: string; group_id?: string | null },
  ): Promise<AssetImportPreview> => {
    const formData = new FormData()
    formData.append('file', file)
    if (options?.date_format) formData.append('date_format', options.date_format)
    if (options?.group_id) formData.append('group_id', options.group_id)
    if (options?.column_mapping && Object.keys(options.column_mapping).length > 0) {
      formData.append('column_mapping', JSON.stringify(options.column_mapping))
    }
    const { data } = await api.post('/assets/import/preview', formData, readOnly)
    return data
  },
  importOrders: async (
    orders: AssetOrderImport[],
    group_id?: string | null,
    filename?: string,
  ): Promise<AssetImportResult> => {
    const { data } = await api.post('/assets/import', { orders, group_id: group_id || null, filename })
    return data
  },
  importTemplate: async (): Promise<void> => {
    const { data } = await api.get('/assets/import/template', { responseType: 'blob' })
    const url = URL.createObjectURL(new Blob([data], { type: 'text/csv;charset=utf-8;' }))
    const a = document.createElement('a')
    a.href = url
    a.download = 'securo-asset-orders.csv'
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
  },
}

// Asset Groups ("wallets")
export const assetGroups = {
  list: async (): Promise<AssetGroup[]> => {
    const { data } = await api.get('/asset-groups')
    return data
  },
  create: async (group: Partial<AssetGroup> & { name: string }): Promise<AssetGroup> => {
    const { data } = await api.post('/asset-groups', group)
    return data
  },
  update: async (id: string, group: Partial<AssetGroup>): Promise<AssetGroup> => {
    const { data } = await api.patch(`/asset-groups/${id}`, group)
    return data
  },
  delete: async (id: string): Promise<void> => {
    await api.delete(`/asset-groups/${id}`)
  },
}

// Collections — user-defined account groups for filtering (issue #105)
export const collections = {
  list: async (): Promise<Collection[]> => {
    const { data } = await api.get('/collections')
    return data
  },
  create: async (payload: { name: string; icon?: string; color?: string; account_ids?: string[]; wallet_ids?: string[] }): Promise<Collection> => {
    const { data } = await api.post('/collections', payload)
    return data
  },
  update: async (id: string, payload: Partial<{ name: string; icon: string; color: string; position: number; account_ids: string[]; wallet_ids: string[] }>): Promise<Collection> => {
    const { data } = await api.patch(`/collections/${id}`, payload)
    return data
  },
  delete: async (id: string): Promise<void> => {
    await api.delete(`/collections/${id}`)
  },
}

// Reports
export const reports = {
  netWorth: async (
    months = 12,
    interval = 'monthly',
    accountIds?: string[],
    assetGroupIds?: string[],
    period?: 'ytd',
    startDate?: string,
    endDate?: string,
  ): Promise<ReportResponse> => {
    const hasFilter = (accountIds && accountIds.length > 0) || (assetGroupIds && assetGroupIds.length > 0)
    const { data } = await api.get('/reports/net-worth', {
      params: {
        months, interval, period,
        ...(startDate && endDate ? { start_date: startDate, end_date: endDate } : {}),
        ...(accountIds && accountIds.length > 0 ? { account_ids: accountIds } : {}),
        ...(assetGroupIds && assetGroupIds.length > 0 ? { asset_group_ids: assetGroupIds } : {}),
      },
      ...(hasFilter ? { paramsSerializer: { indexes: null as null } } : {}),
    })
    return data
  },
  // `days` requests an exact rolling window ending today, instead of the
  // month-aligned window `months` produces. `startDate`/`endDate` (both
  // required together) pin the window to an explicit calendar range and
  // override the preset selectors on the backend.
  incomeExpenses: async (
    months = 12,
    interval = 'monthly',
    accountIds?: string[],
    period?: 'ytd',
    days?: number,
    startDate?: string,
    endDate?: string,
  ): Promise<ReportResponse> => {
    const extra = acctIdsParam(accountIds)
    const { data } = await api.get('/reports/income-expenses', {
      params: {
        months, interval, period, days,
        ...(startDate && endDate ? { start_date: startDate, end_date: endDate } : {}),
        ...(extra.params ?? {}),
      },
      ...(extra.paramsSerializer ? { paramsSerializer: extra.paramsSerializer } : {}),
    })
    return data
  },
  cashFlow: async (months = 6, interval = 'daily', baseline = false, accountIds?: string[]): Promise<ReportResponse> => {
    const extra = acctIdsParam(accountIds)
    const { data } = await api.get('/reports/cash-flow', { params: { months, interval, baseline, ...(extra.params ?? {}) }, ...(extra.paramsSerializer ? { paramsSerializer: extra.paramsSerializer } : {}) })
    return data
  },
  // Oldest and newest transaction dates in the workspace (opening
  // balances excluded). The reports page builds its year picker from
  // these bounds (issue #765).
  dataRange: async (): Promise<{ min_date: string | null; max_date: string | null }> => {
    const { data } = await api.get('/reports/data-range')
    return data
  },
}

// Currencies
export const currencies = {
  list: async (): Promise<{ code: string; symbol: string; name: string; flag: string }[]> => {
    const { data } = await api.get('/currencies')
    return data
  },
}

// FX Rates
export const fxRates = {
  refresh: async (): Promise<{ synced: boolean; rates_count: number; date: string }> => {
    const { data } = await api.post('/fx-rates/refresh')
    return data
  },
  status: async (): Promise<{ last_sync_date: string | null; total_rates: number }> => {
    const { data } = await api.get('/fx-rates/status')
    return data
  },
}

// Import Logs
export const importLogs = {
  list: async (): Promise<ImportLog[]> => {
    const { data } = await api.get('/import-logs')
    return data
  },
  delete: async (id: string): Promise<void> => {
    await api.delete(`/import-logs/${id}`)
  },
}

// Settings
export const settings = {
  attachments: async (): Promise<{ allowed_extensions: string[]; max_file_size_mb: number; max_attachments_per_transaction: number }> => {
    const { data } = await api.get('/settings/attachments')
    return data
  },
}

// Backup
export const backup = {
  /**
   * Download the workspace archive, encrypted with AES-256 when a password is
   * given. POST rather than GET so the password stays out of browser history
   * and proxy logs.
   */
  download: async (password?: string): Promise<void> => {
    const { data } = await api.post(
      '/export/backup',
      password ? { password } : {},
      { ...readOnly, responseType: 'blob' },
    )
    const blob = new Blob([data], { type: 'application/zip' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `securo-backup-${new Date().toISOString().slice(0, 10)}.zip`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
  },
}

// Admin
export interface TimezoneSetting {
  /** The timezone in use, after fallbacks. */
  timezone: string
  /** What an administrator saved, valid or not; null when nothing is saved. */
  saved: string | null
  /** Where the application lands without a saved value. */
  fallback: string
  available: string[]
}

export const timezones = {
  list: async (): Promise<{ default: string; available: string[] }> => {
    const { data } = await api.get('/timezones')
    return data
  },
}

export const admin = {
  listUsers: async (params?: { search?: string; page?: number; limit?: number }): Promise<AdminUserList> => {
    const { data } = await api.get('/admin/users', { params })
    return data
  },
  getUser: async (id: string): Promise<AdminUser> => {
    const { data } = await api.get(`/admin/users/${id}`)
    return data
  },
  createUser: async (user: { email: string; password: string; is_superuser?: boolean; preferences?: Record<string, unknown> }): Promise<AdminUser> => {
    const { data } = await api.post('/admin/users', user)
    return data
  },
  updateUser: async (id: string, user: Partial<{ email: string; password: string; is_active: boolean; is_superuser: boolean; preferences: Record<string, unknown> }>): Promise<AdminUser> => {
    const { data } = await api.patch(`/admin/users/${id}`, user)
    return data
  },
  deleteUser: async (id: string): Promise<void> => {
    await api.delete(`/admin/users/${id}`)
  },
  getSetting: async (key: string): Promise<AppSetting> => {
    const { data } = await api.get(`/admin/settings/${key}`)
    return data
  },
  updateSetting: async (key: string, value: string): Promise<AppSetting> => {
    const { data } = await api.patch(`/admin/settings/${key}`, { value })
    return data
  },
  deleteSetting: async (key: string): Promise<void> => {
    await api.delete(`/admin/settings/${key}`)
  },
  timezone: async (): Promise<TimezoneSetting> => {
    const { data } = await api.get('/admin/timezone')
    return data
  },
  registrationStatus: async (): Promise<{ enabled: boolean }> => {
    const { data } = await api.get('/admin/registration-status')
    return data
  },
  accountingMode: async (): Promise<{ mode: 'cash' | 'accrual' }> => {
    const { data } = await api.get('/admin/accounting-mode')
    return data
  },
  numberFormat: async (): Promise<{ format: NumberFormat }> => {
    const { data } = await api.get('/admin/number-format')
    return data
  },
  dateFormat: async (): Promise<{ format: DateFormat }> => {
    const { data } = await api.get('/admin/date-format')
    return data
  },
  defaultColors: async (): Promise<{ light: string | null; dark: string | null }> => {
    const { data } = await api.get('/admin/default-colors')
    return data
  },
}

// Global search (powers the command palette)
export type SearchHitType =
  | 'transaction'
  | 'account'
  | 'payee'
  | 'category'
  | 'goal'
  | 'asset'

export interface SearchHit {
  type: SearchHitType
  id: string
  label: string
  subtitle: string | null
  amount: number | null
  currency: string | null
  date: string | null
  icon: string | null
  color: string | null
  meta: Record<string, unknown>
}

export const search = {
  query: async (q: string, limit = 5): Promise<SearchHit[]> => {
    if (!q.trim()) return []
    const { data } = await api.get('/search', { params: { q, limit } })
    return data.results as SearchHit[]
  },
}

// App-level feature flags (whether optional modules like agents are mounted)
export interface AppInfo {
  features: { agents: boolean; tesouro_direto?: boolean }
}

export const info = {
  get: async (): Promise<AppInfo> => {
    const { data } = await api.get('/info')
    return data
  },
}

// Agents / MCP / RAG -- only meaningful when info.features.agents === true.
export interface Agent {
  id: string
  name: string
  description: string | null
  system_prompt: string
  icon: string
  color: string
  connection_id: string | null
  provider: string | null
  model: string | null
  temperature: number
  max_history_messages: number
  top_n: number
  similarity_threshold: number
  extra: Record<string, unknown>
  auto_context: boolean
  is_archived: boolean
  is_default: boolean
  // Populated by GET /agents (list endpoint) for the agents page.
  // Single-agent endpoints leave them at 0 since the row-level page
  // already shows tabs for both lists.
  conversation_count: number
  knowledge_count: number
  created_at: string
  updated_at: string
}

export type LlmConnectionKind = 'ollama' | 'openai' | 'anthropic' | 'openai_compatible'

export interface LlmConnection {
  id: string
  name: string
  kind: LlmConnectionKind
  base_url: string | null
  default_model: string | null
  extra: Record<string, unknown>
  is_default: boolean
  has_api_key: boolean
  created_at: string
  updated_at: string
}

export interface LlmConnectionPayload {
  name: string
  kind: LlmConnectionKind
  base_url?: string | null
  api_key?: string | null
  default_model?: string | null
  extra?: Record<string, unknown>
  is_default?: boolean
}

export interface LlmConnectionTestResult {
  ok: boolean
  detail: string
  models?: string[]
}

export interface AgentConversation {
  id: string
  agent_id: string
  channel: string
  title: string | null
  created_at: string
  updated_at: string
}

export interface AgentMessage {
  id: string
  role: 'system' | 'user' | 'assistant' | 'tool'
  ordinal: number
  content: string | null
  tool_calls: Array<{ id: string; name: string; arguments: Record<string, unknown> }> | null
  tool_result: { tool_call_id?: string; name?: string; data?: unknown; ok?: boolean } | null
  citations: unknown[] | null
  input_tokens: number | null
  output_tokens: number | null
  created_at: string
}

export interface AgentToolHandle {
  server: string
  name: string
  description: string
  is_proposal: boolean
  enabled: boolean
}

export interface KnowledgeDoc {
  id: string
  agent_id: string
  title: string
  source: string | null
  mime: string
  size_bytes: number
  status: 'pending' | 'processing' | 'ready' | 'failed'
  error: string | null
  chunk_count: number
  pinned: boolean
  created_at: string
  updated_at: string
}

export const agents = {
  info: async () => {
    const { data } = await api.get('/agents/info')
    return data as {
      enabled: boolean
      providers: string[]
      embedding_dim: number
      default_top_n: number
      default_similarity_threshold: number
      extra_mcp_servers_configured: boolean
      mcp_external_ttl_days: number
      external_mcp_url: string
    }
  },
  mcpTokens: {
    create: async (): Promise<{ token: string; expires_in_seconds: number; expires_in_days: number }> => {
      const { data } = await api.post('/agents/mcp-tokens')
      return data
    },
  },
  list: async (includeArchived = false): Promise<Agent[]> => {
    const { data } = await api.get('/agents', { params: { include_archived: includeArchived } })
    return data
  },
  // Default agent for the global slide-over chat panel. Returns the
  // user-flagged default; falls back to the most recent agent.
  // Throws 404 if the user has no agents at all.
  getDefault: async (): Promise<Agent> => {
    const { data } = await api.get('/agents/default')
    return data
  },
  get: async (id: string): Promise<Agent> => {
    const { data } = await api.get(`/agents/${id}`)
    return data
  },
  create: async (
    payload: Partial<Agent> & {
      name: string
      /** Tool whitelist saved with the agent in the same transaction. */
      tools?: { server: string; tool_name: string; enabled: boolean }[]
    },
  ): Promise<Agent> => {
    const { data } = await api.post('/agents', payload)
    return data
  },
  update: async (id: string, payload: Partial<Agent>): Promise<Agent> => {
    const { data } = await api.patch(`/agents/${id}`, payload)
    return data
  },
  remove: async (id: string): Promise<void> => {
    await api.delete(`/agents/${id}`)
  },
  tools: async (id: string): Promise<{ servers: { name: string }[]; tools: AgentToolHandle[] }> => {
    const { data } = await api.get(`/agents/${id}/tools`)
    return data
  },
  setTools: async (id: string, items: { server: string; tool_name: string; enabled: boolean }[]): Promise<void> => {
    await api.put(`/agents/${id}/tools`, items)
  },
  knowledge: {
    list: async (id: string): Promise<{ items: KnowledgeDoc[]; total: number }> => {
      const { data } = await api.get(`/agents/${id}/knowledge`)
      return data
    },
    upload: async (id: string, file: File, pinned = false): Promise<KnowledgeDoc> => {
      const fd = new FormData()
      fd.append('file', file)
      fd.append('pinned', String(pinned))
      const { data } = await api.post(`/agents/${id}/knowledge`, fd)
      return data
    },
    pin: async (agentId: string, docId: string, pinned: boolean): Promise<KnowledgeDoc> => {
      const { data } = await api.patch(`/agents/${agentId}/knowledge/${docId}/pin`, null, {
        params: { pinned },
      })
      return data
    },
    remove: async (agentId: string, docId: string): Promise<void> => {
      await api.delete(`/agents/${agentId}/knowledge/${docId}`)
    },
  },
  conversations: {
    list: async (agentId?: string, limit = 50): Promise<AgentConversation[]> => {
      const { data } = await api.get('/agents/conversations', { params: { agent_id: agentId, limit } })
      return data
    },
    get: async (id: string): Promise<AgentConversation> => {
      const { data } = await api.get(`/agents/conversations/${id}`)
      return data
    },
    messages: async (id: string, limit = 200): Promise<AgentMessage[]> => {
      const { data } = await api.get(`/agents/conversations/${id}/messages`, { params: { limit } })
      return data
    },
    rename: async (id: string, title: string): Promise<AgentConversation> => {
      const { data } = await api.patch(`/agents/conversations/${id}`, { title })
      return data
    },
    generateTitle: async (id: string): Promise<AgentConversation> => {
      const { data } = await api.post(`/agents/conversations/${id}/generate-title`)
      return data
    },
    remove: async (id: string): Promise<void> => {
      await api.delete(`/agents/conversations/${id}`)
    },
  },
  // Streaming chat endpoint — caller handles the SSE response themselves
  // (see lib/agents-stream.ts). We just expose the URL + body builder.
  chatUrl: (agentId: string) => `/api/agents/${agentId}/chat`,

  connections: {
    list: async (): Promise<LlmConnection[]> => {
      const { data } = await api.get('/agents/connections')
      return data
    },
    get: async (id: string): Promise<LlmConnection> => {
      const { data } = await api.get(`/agents/connections/${id}`)
      return data
    },
    create: async (payload: LlmConnectionPayload): Promise<LlmConnection> => {
      const { data } = await api.post('/agents/connections', payload)
      return data
    },
    update: async (id: string, payload: Partial<LlmConnectionPayload>): Promise<LlmConnection> => {
      const { data } = await api.patch(`/agents/connections/${id}`, payload)
      return data
    },
    remove: async (id: string): Promise<void> => {
      await api.delete(`/agents/connections/${id}`)
    },
    test: async (id: string): Promise<LlmConnectionTestResult> => {
      const { data } = await api.post(`/agents/connections/${id}/test`, undefined, readOnly)
      return data
    },
  },
}

export default api

// Invoices — business workspaces only. Every route 404s for a workspace
// without the module, so these are never called from a personal one.
export interface InvoiceWritePayload {
  direction?: InvoiceDirection
  /** Keep it a draft even where the workspace would open it on creation.
   *  Not a status field — only the difference between "still writing
   *  this" and "this is owed". Ignored on update. */
  as_draft?: boolean
  /** Provenance, for anything that did not originate here: a gateway
   *  sync, a forwarded email, a photographed supplier invoice. */
  origin?: 'local' | 'imported'
  external_source?: string
  external_id?: string
  payee_id?: string | null
  issue_date?: string
  due_date?: string
  competence_date?: string | null
  currency?: string
  total?: string
  discount?: string
  notes?: string | null
  internal_notes?: string | null
  custom_fields?: Record<string, string> | null
  lines?: InvoiceLineInput[]
  /** More than one due date. Must add up to the total; an empty list clears it. */
  installments?: InstallmentInput[]
}

export interface MakeRecurringPayload {
  frequency: InvoiceScheduleFrequency
  start_date?: string
  name?: string
  end_type?: InvoiceScheduleEndType
  end_date?: string | null
  end_count?: number | null
  payment_terms_days?: number | null
}

export interface InvoiceScheduleWritePayload {
  name?: string
  payee_id?: string | null
  frequency?: InvoiceScheduleFrequency
  start_date?: string
  end_type?: InvoiceScheduleEndType
  end_date?: string | null
  end_count?: number | null
  payment_terms_days?: number | null
  currency?: string
  notes?: string | null
  custom_fields?: Record<string, string> | null
  /** Create only: the first term, in force from `start_date`. */
  lines?: InvoiceLineInput[]
  discount?: string | null
}

export interface InvoiceScheduleTermPayload {
  effective_from?: string
  lines?: InvoiceLineInput[]
  discount?: string | null
}

/** Recurring invoices: an agreement that emits one invoice per period.
 *  Its own prefix, because `/invoices/{id}` would swallow `schedules`. */
export const invoiceSchedules = {
  list: async (params?: { status?: InvoiceScheduleStatus; payee_id?: string }): Promise<InvoiceSchedule[]> => {
    const { data } = await api.get('/invoice-schedules', { params })
    return data
  },
  summary: async (): Promise<InvoiceScheduleSummary> => {
    const { data } = await api.get('/invoice-schedules/summary')
    return data
  },
  get: async (id: string): Promise<InvoiceSchedule> => {
    const { data } = await api.get(`/invoice-schedules/${id}`)
    return data
  },
  invoices: async (id: string): Promise<Invoice[]> => {
    const { data } = await api.get(`/invoice-schedules/${id}/invoices`)
    return data
  },
  periods: async (id: string, ahead = 3): Promise<InvoiceSchedulePeriod[]> => {
    const { data } = await api.get(`/invoice-schedules/${id}/periods`, { params: { ahead } })
    return data
  },
  create: async (payload: InvoiceScheduleWritePayload): Promise<InvoiceSchedule> => {
    const { data } = await api.post('/invoice-schedules', payload)
    return data
  },
  update: async (id: string, payload: InvoiceScheduleWritePayload): Promise<InvoiceSchedule> => {
    const { data } = await api.patch(`/invoice-schedules/${id}`, payload)
    return data
  },
  remove: async (id: string): Promise<void> => {
    await api.delete(`/invoice-schedules/${id}`)
  },
  pause: async (id: string): Promise<InvoiceSchedule> => {
    const { data } = await api.post(`/invoice-schedules/${id}/pause`)
    return data
  },
  resume: async (id: string): Promise<InvoiceSchedule> => {
    const { data } = await api.post(`/invoice-schedules/${id}/resume`)
    return data
  },
  end: async (id: string, payload: { reason: InvoiceScheduleEndReason; ended_at?: string }): Promise<InvoiceSchedule> => {
    const { data } = await api.post(`/invoice-schedules/${id}/end`, payload)
    return data
  },
  /** Emit the next period now, whether or not its date has come. */
  generate: async (id: string): Promise<Invoice[]> => {
    const { data } = await api.post(`/invoice-schedules/${id}/generate`)
    return data
  },
  addTerm: async (id: string, payload: InvoiceScheduleTermPayload): Promise<InvoiceSchedule> => {
    const { data } = await api.post(`/invoice-schedules/${id}/terms`, payload)
    return data
  },
  updateTerm: async (id: string, termId: string, payload: InvoiceScheduleTermPayload): Promise<InvoiceSchedule> => {
    const { data } = await api.patch(`/invoice-schedules/${id}/terms/${termId}`, payload)
    return data
  },
  removeTerm: async (id: string, termId: string): Promise<InvoiceSchedule> => {
    const { data } = await api.delete(`/invoice-schedules/${id}/terms/${termId}`)
    return data
  },
  /** Say an existing invoice answers for a period of this agreement. */
  link: async (id: string, payload: { invoice_id: string; period_start: string }): Promise<Invoice> => {
    const { data } = await api.post(`/invoice-schedules/${id}/link`, payload)
    return data
  },
}

export const invoices = {
  facets: async (year?: number, direction?: InvoiceDirection): Promise<InvoiceFacets> => {
    const { data } = await api.get('/invoices/facets', {
      params: { ...(year ? { year } : {}), ...(direction ? { direction } : {}) },
    })
    return data
  },
  list: async (params?: { state?: string; year?: number; direction?: InvoiceDirection; payee_id?: string; schedule_id?: string; q?: string; limit?: number } | Record<string, unknown>): Promise<Invoice[]> => {
    const cleanParams = params && !('queryKey' in params) ? params : undefined
    const { data } = await api.get('/invoices', { params: cleanParams })
    return data
  },
  get: async (id: string): Promise<Invoice> => {
    const { data } = await api.get(`/invoices/${id}`)
    return data
  },
  summary: async (direction?: InvoiceDirection): Promise<InvoiceSummary> => {
    const { data } = await api.get('/invoices/summary', {
      params: direction ? { direction } : undefined,
    })
    return data
  },
  create: async (payload: InvoiceWritePayload): Promise<Invoice> => {
    const { data } = await api.post('/invoices', payload)
    return data
  },
  update: async (id: string, payload: InvoiceWritePayload): Promise<Invoice> => {
    const { data } = await api.patch(`/invoices/${id}`, payload)
    return data
  },
  remove: async (id: string): Promise<void> => {
    await api.delete(`/invoices/${id}`)
  },
  /** Turn this invoice into period one of a new agreement that repeats it. */
  makeRecurring: async (id: string, payload: MakeRecurringPayload): Promise<InvoiceSchedule> => {
    const { data } = await api.post(`/invoices/${id}/make-recurring`, payload)
    return data
  },
  /** The invoice stops answering for a period. It stays as it is. */
  unlinkSchedule: async (id: string): Promise<Invoice> => {
    const { data } = await api.delete(`/invoices/${id}/schedule`)
    return data
  },
  // The decisions. Each is its own call for the same reason it is its own
  // route on the server: a status change always has a cause.
  issue: async (id: string): Promise<Invoice> => {
    const { data } = await api.post(`/invoices/${id}/issue`)
    return data
  },
  void: async (id: string): Promise<Invoice> => {
    const { data } = await api.post(`/invoices/${id}/void`)
    return data
  },
  writeOff: async (id: string): Promise<Invoice> => {
    const { data } = await api.post(`/invoices/${id}/uncollectible`)
    return data
  },
  reopen: async (id: string): Promise<Invoice> => {
    const { data } = await api.post(`/invoices/${id}/reopen`)
    return data
  },
  allocate: async (id: string, transactionId: string, amount?: string): Promise<Invoice> => {
    const { data } = await api.post(`/invoices/${id}/allocations`, {
      transaction_id: transactionId,
      ...(amount ? { amount } : {}),
    })
    return data
  },
  /** Close part of the debt without money: tax withheld, a fee kept. */
  deduct: async (
    id: string,
    payload: { kind: DeductionKind; amount: string; tax_kind?: string | null; note?: string | null; transaction_id?: string | null },
  ): Promise<Invoice> => {
    const { data } = await api.post(`/invoices/${id}/deductions`, payload)
    return data
  },
  undeduct: async (id: string, deductionId: string): Promise<Invoice> => {
    const { data } = await api.delete(`/invoices/${id}/deductions/${deductionId}`)
    return data
  },
  unallocate: async (id: string, allocationId: string): Promise<Invoice> => {
    const { data } = await api.delete(`/invoices/${id}/allocations/${allocationId}`)
    return data
  },
  settings: async (): Promise<InvoiceSettings> => {
    const { data } = await api.get('/invoices/settings')
    return data
  },
  updateSettings: async (payload: Partial<InvoiceSettings>): Promise<InvoiceSettings> => {
    const { data } = await api.patch('/invoices/settings', payload)
    return data
  },
  issuer: async (): Promise<IssuerProfile> => {
    const { data } = await api.get('/invoices/issuer')
    return data
  },
  updateIssuer: async (payload: {
    legal_name?: string | null
    address?: string | null
    tax_ids?: IssuerTaxId[]
  }): Promise<IssuerProfile> => {
    const { data } = await api.patch('/invoices/issuer', payload)
    return data
  },
  document: async (id: string): Promise<InvoiceDocumentPayload> => {
    const { data } = await api.get(`/invoices/${id}/document`)
    return data
  },
  /** Fetched as a blob rather than linked directly: the PDF route needs
   *  the Authorization header and the workspace header the interceptor
   *  adds, which a plain <a href> would not carry. */
  pdf: async (id: string): Promise<Blob> => {
    const { data } = await api.get(`/invoices/${id}/pdf`, { responseType: 'blob' })
    return data
  },
  /** The statement of account: payments and deductions since issue. */
  statement: async (id: string): Promise<Blob> => {
    const { data } = await api.get(`/invoices/${id}/statement`, { responseType: 'blob' })
    return data
  },
  share: async (id: string): Promise<InvoiceShareLink> => {
    const { data } = await api.post(`/invoices/${id}/share`)
    return data
  },
  unshare: async (id: string): Promise<void> => {
    await api.delete(`/invoices/${id}/share`)
  },
  /** The workspace's mark. Uploaded rather than linked, so a rendered
   *  document never fetches an image from somebody else's host. */
  uploadLogo: async (file: File): Promise<InvoiceSettings> => {
    const form = new FormData()
    form.append('file', file)
    const { data } = await api.post('/invoices/settings/logo', form)
    return data
  },
  removeLogo: async (): Promise<InvoiceSettings> => {
    const { data } = await api.delete('/invoices/settings/logo')
    return data
  },
  /** By id, not "the current one": a document issued under an older mark
   *  froze that id, and asking for the current logo would repaint it. */
  logoUrl: async (logoId: string): Promise<string> => {
    const { data } = await api.get(`/invoices/logo/${logoId}`, { responseType: 'blob' })
    return URL.createObjectURL(data)
  },
  /** The paper gathered under an invoice: the bill, the fiscal document,
   *  a receipt, the contract behind it. */
  attachments: {
    list: async (invoiceId: string): Promise<InvoiceAttachment[]> => {
      const { data } = await api.get(`/invoices/${invoiceId}/attachments`)
      return data
    },
    upload: async (
      invoiceId: string,
      file: File,
      fields: { kind?: string; document_number?: string; issued_at?: string; is_primary?: boolean } = {},
    ): Promise<InvoiceAttachment> => {
      const form = new FormData()
      form.append('file', file)
      Object.entries(fields).forEach(([key, value]) => {
        if (value !== undefined && value !== null && value !== '') form.append(key, String(value))
      })
      const { data } = await api.post(`/invoices/${invoiceId}/attachments`, form)
      return data
    },
    /** Same reason as `pdf` above: the route needs headers a plain
     *  <a href> would not carry, so the bytes come back as a blob. */
    blobUrl: async (invoiceId: string, attachmentId: string): Promise<string> => {
      const { data } = await api.get(`/invoices/${invoiceId}/attachments/${attachmentId}`, {
        responseType: 'blob',
      })
      return URL.createObjectURL(data)
    },
    update: async (
      invoiceId: string,
      attachmentId: string,
      payload: Partial<Pick<InvoiceAttachment, 'kind' | 'document_number' | 'issued_at' | 'is_primary'>>,
    ): Promise<InvoiceAttachment> => {
      const { data } = await api.patch(`/invoices/${invoiceId}/attachments/${attachmentId}`, payload)
      return data
    },
    remove: async (invoiceId: string, attachmentId: string): Promise<void> => {
      await api.delete(`/invoices/${invoiceId}/attachments/${attachmentId}`)
    },
  },
}

/** The shared invoice. Unauthenticated by design — the token is the whole
 *  credential — so these bypass the api instance and its interceptors. */
export const publicInvoices = {
  get: async (token: string): Promise<InvoiceDocumentPayload> => {
    // Bare axios, not the shared instance: the interceptors would attach
    // an Authorization header and a workspace id, and this route must
    // work for someone who has neither.
    const { data } = await axios.get(`/api/public/invoices/${token}`)
    return data
  },
  pdfUrl: (token: string): string => `/api/public/invoices/${token}/pdf`,
}