/**
 * Expense shared types — expenses-module.
 * Consumed by @zync/expenses service layer, zync-api routes, and zync-app UI.
 */
import type { ExpenseCategoryId } from './expense-categories'

export type ExpenseStatus = 'PENDING' | 'PROCESSING' | 'COMPLETED' | 'FAILED' | 'NEEDS_REVIEW'
export type ExpenseSource = 'upload' | 'email' | 'whatsapp' | 'telegram'
export type CorrectionSource = 'ocr' | 'manual'
export type ExpenseBillingStatus = 'billed' | 'unbilled' | 'no_project'

/** Confidence threshold constants for OCR routing — expense-ocr-correction-ux spec. */
export const OCR_CONFIDENCE_AUTO_COMPLETE = 0.85
export const OCR_CONFIDENCE_REVIEW_FLOOR = 0.60

export interface PerDiemRates {
  domestic_full_day: number
  domestic_half_day: number
  international_full_day: number
  international_half_day: number
}

/**
 * Canonical @zync/types shape for tenant_settings expense config columns.
 * snake_case matches column names. Currency is NOT here — tenants.default_currency scalar.
 * expense-settings-ui (spec 62) imports this; it does not redefine it.
 */
export interface ExpenseSettings {
  filing_cadence: 'monthly' | 'bimonthly'
  tax_basis: 'cash' | 'accrual'
  business_category: string | null
  per_diem_rates: PerDiemRates
  expense_default_category: string
  expense_auto_approve_threshold_ils: number
  expense_receipt_reminder_enabled: boolean
  expense_receipt_reminder_days: number
  expense_approval_threshold_ils: number
  expense_approver_role: string
}

export interface Expense {
  id: string
  tenantId: string
  projectId: string | null
  createdBy: string
  r2Key: string
  fileName: string
  fileType: 'pdf' | 'jpg' | 'png' | 'heic'
  fileSizeBytes: number
  vendorName: string | null
  vendorTaxId: string | null
  invoiceNumber: string | null
  invoiceTotal: string | null
  vatAmount: string | null
  currency: string
  allocationNumber: string | null
  rawOcrText: string | null
  expenseDate: string | null
  amount: string | null
  businessAmount: string | null
  personalAmount: string | null
  vatDeductible: boolean
  status: ExpenseStatus
  ocrConfidence: string | null
  processingStartedAt: string | null
  processedAt: string | null
  processingError: string | null
  expenseCategory: ExpenseCategoryId | null
  deductionPct: number | null
  deductionConfidence: string | null
  deductionReasoningHe: string | null
  deductionReasoningEn: string | null
  evaluatedAt: string | null
  isPerDiem: boolean
  perDiemDays: string | null
  perDiemRateIls: string | null
  source: ExpenseSource
  sourceMetadata: Record<string, unknown> | null
  notes: string | null
  businessPercent: number
  billedAt: string | null
  invoiceId: string | null
  billingStatus: ExpenseBillingStatus
  // ── OCR correction UX fields ──────────────────────────────────────────────
  correctionNote: string | null
  voidedAt: string | null
  voidedReason: string | null
  // ── Approval workflow ─────────────────────────────────────────────────────
  approvalStatus: string
  approvedBy: string | null
  approvedAt: string | null
  approvalNote: string | null
  createdAt: string
  updatedAt: string
}

export interface ExpenseCorrection {
  id: string
  expenseId: string
  userId: string
  fieldName: string
  originalValue: string | null
  correctedValue: string
  correctionSource: CorrectionSource
  createdAt: string
}

/** Review queue item — GET /api/expenses/review response shape */
export interface ReviewQueueItem {
  id: string
  tenantId: string
  vendorName: string | null
  amount: string | null
  currency: string
  expenseDate: string | null
  ocrConfidence: string | null
  status: ExpenseStatus
  createdAt: string
}

export interface ReviewQueueResponse {
  items: ReviewQueueItem[]
  nextCursor: string | null
  total: number
}

/** POST /api/expenses/:id/approve body */
export interface ApproveOcrExpenseInput {
  corrections: Record<string, string>
}

/** POST /api/expenses/:id/correct body */
export interface CorrectExpenseInput {
  reason: string
  amount?: string
  category?: string
  date?: string
  receiptR2Key?: string
}

/** POST /api/expenses/:id/void body */
export interface VoidExpenseInput {
  reason: string
}

export interface ExpenseListResponse {
  items: Expense[]
  nextCursor: string | null
  total: number
}

/**
 * Status badge color tiers for UI display (same mapping used by serializers and UI).
 */
export const EXPENSE_STATUS_BADGES: Record<ExpenseStatus, { label: string; variant: 'default' | 'success' | 'warning' | 'error' | 'secondary' | 'outline' }> = {
  PENDING:      { label: 'Pending',      variant: 'default'  },
  PROCESSING:   { label: 'Processing',   variant: 'warning'  },
  COMPLETED:    { label: 'Completed',    variant: 'success'  },
  FAILED:       { label: 'Failed',       variant: 'error'    },
  NEEDS_REVIEW: { label: 'Needs Review', variant: 'warning'  },
}

/**
 * Confidence tier helper — used by API serializers and the expense table UI.
 * Returns a color tier based on OCR/deduction confidence score.
 */
export function confidenceTier(c: number): 'success' | 'warning' | 'error' {
  if (c >= 0.9) return 'success'
  if (c >= 0.7) return 'warning'
  return 'error'
}
