/**
 * SAMMS Enterprise - Core Type Definitions
 */

// ============================================================
// Common Types
// ============================================================

export interface BaseEntity {
  id: string
  created_at: string
  updated_at: string
}

export interface PaginationParams {
  page?: number
  per_page?: number
  sort_by?: string
  sort_order?: 'asc' | 'desc'
  search?: string
}

export interface PaginatedResponse<T> {
  data: T[]
  meta: {
    page: number
    per_page: number
    total: number
    total_pages: number
  }
}

export interface SelectOption {
  value: string
  label: string
  description?: string
  disabled?: boolean
}

export interface TreeNode<T> {
  id: string
  name: string
  children?: TreeNode<T>[]
  data?: T
  expanded?: boolean
  selected?: boolean
}

export interface BreadcrumbItem {
  label: string
  href?: string
  icon?: string
}

export interface StatusBadge {
  variant: 'default' | 'success' | 'warning' | 'destructive' | 'info' | 'muted'
  label: string
}

// ============================================================
// User & Auth Types
// ============================================================

export interface User extends BaseEntity {
  email: string
  username: string
  first_name: string
  last_name: string
  display_name: string
  avatar_url?: string
  phone?: string
  timezone: string
  locale: string
  is_active: boolean
  is_verified: boolean
  is_superuser: boolean
  mfa_enabled: boolean
  roles: Role[]
  permissions: string[]
  last_login_at?: string
  preferences: UserPreferences
}

export interface Role {
  id: string
  name: string
  display_name: string
  description?: string
  permissions: string[]
  is_system: boolean
}

export interface UserPreferences {
  theme: 'light' | 'dark' | 'system'
  language: string
  date_format: string
  time_format: '12h' | '24h'
  number_format: string
  currency: string
  timezone: string
  email_notifications: boolean
  push_notifications: boolean
  dashboard_layout?: Record<string, unknown>
  sidebar_collapsed: boolean
  default_company_id?: string
}

export interface AuthState {
  user: User | null
  access_token: string | null
  refresh_token: string | null
  isAuthenticated: boolean
  isLoading: boolean
  error?: string
}

export interface LoginCredentials {
  email: string
  password: string
  mfa_code?: string
  remember_me?: boolean
}

export interface AuthResponse {
  access_token: string
  refresh_token: string
  expires_in: number
  user: User
}

export interface ApiKey extends BaseEntity {
  name: string
  prefix: string
  scopes: string[]
  expires_at?: string
  last_used_at?: string
  created_by: string
}

// ============================================================
// Company Types
// ============================================================

export interface Company extends BaseEntity {
  code: string
  name: string
  legal_name: string
  description?: string
  type: CompanyType
  status: CompanyStatus
  parent_id?: string
  logo_url?: string
  branding: CompanyBranding
  address: Address
  contact: ContactInfo
  settings: CompanySettings
  fiscal_year_start: number
  base_currency: string
  timezone: string
  subscription?: Subscription
  children?: Company[]
}

export type CompanyType = 'holding' | 'parent' | 'subsidiary' | 'division' | 'branch'
export type CompanyStatus = 'active' | 'inactive' | 'suspended' | 'pending'

export interface CompanyBranding {
  primary_color: string
  secondary_color: string
  logo_url?: string
  favicon_url?: string
  custom_css?: string
}

export interface Address {
  line1: string
  line2?: string
  city: string
  state: string
  postal_code: string
  country: string
}

export interface ContactInfo {
  email: string
  phone?: string
  fax?: string
  website?: string
}

export interface CompanySettings {
  date_format: string
  number_format: string
  default_payment_terms: number
  enable_multicurrency: boolean
  enable_approval_workflows: boolean
  require_2fa: boolean
  session_timeout: number
  ip_whitelist: string[]
  features: Record<string, boolean>
}

export interface Subscription {
  plan: string
  status: 'active' | 'past_due' | 'canceled' | 'trialing'
  current_period_start: string
  current_period_end: string
  seats: number
  limits: Record<string, number>
}

// ============================================================
// Accounting Types
// ============================================================

export interface Account extends BaseEntity {
  code: string
  name: string
  type: AccountType
  subtype?: string
  parent_id?: string
  description?: string
  currency: string
  balance: number
  status: 'active' | 'inactive' | 'locked'
  is_system: boolean
  allow_manual_entry: boolean
  require_third_party: boolean
  normal_balance: 'debit' | 'credit'
  level: number
  path: string
  children?: Account[]
}

export type AccountType = 
  | 'asset' 
  | 'liability' 
  | 'equity' 
  | 'revenue' 
  | 'expense'

export interface JournalEntry extends BaseEntity {
  number: string
  date: string
  description: string
  reference?: string
  status: JournalEntryStatus
  type: JournalEntryType
  reversal_of_id?: string
  fiscal_period_id: string
  lines: JournalEntryLine[]
  total_debit: number
  total_credit: number
  is_balanced: boolean
  created_by: string
  posted_at?: string
  posted_by?: string
  approved_at?: string
  approved_by?: string
  attachments?: Attachment[]
}

export type JournalEntryStatus = 'draft' | 'pending' | 'approved' | 'posted' | 'reversed' | 'voided'
export type JournalEntryType = 'standard' | 'adjusting' | 'closing' | 'reversing' | 'recurring'

export interface JournalEntryLine {
  id: string
  account_id: string
  account_code: string
  account_name: string
  description?: string
  debit: number
  credit: number
  third_party_type?: 'customer' | 'vendor' | 'employee'
  third_party_id?: string
  analytic_code?: string
}

export interface FiscalYear extends BaseEntity {
  name: string
  start_date: string
  end_date: string
  status: 'open' | 'closed' | 'closing'
  periods: FiscalPeriod[]
  is_adjustment_period: boolean
}

export interface FiscalPeriod {
  id: string
  number: number
  name: string
  start_date: string
  end_date: string
  status: 'open' | 'closed' | 'adjustment'
  quarter: number
}

// ============================================================
// Treasury Types
// ============================================================

export interface TreasuryAccount extends BaseEntity {
  code: string
  name: string
  type: TreasuryAccountType
  bank_name?: string
  bank_account_number?: string
  bank_routing_number?: string
  currency: string
  balance: number
  available_balance: number
  credit_limit?: number
  interest_rate?: number
  status: 'active' | 'inactive' | 'frozen' | 'closed'
  is_default: boolean
  reconciled_at?: string
}

export type TreasuryAccountType = 
  | 'checking' 
  | 'savings' 
  | 'money_market' 
  | 'credit_card' 
  | 'line_of_credit' 
  | 'cash'

export interface TreasuryTransaction extends BaseEntity {
  number: string
  treasury_account_id: string
  type: TreasuryTransactionType
  amount: number
  currency: string
  date: string
  value_date?: string
  description: string
  reference?: string
  category?: string
  status: TreasuryTransactionStatus
  reconciled: boolean
  reconciled_at?: string
  payee_payer?: string
  check_number?: string
  attachments?: Attachment[]
}

export type TreasuryTransactionType = 
  | 'deposit' 
  | 'withdrawal' 
  | 'transfer' 
  | 'payment' 
  | 'receipt' 
  | 'adjustment' 
  | 'interest' 
  | 'fee'

export type TreasuryTransactionStatus = 
  | 'pending' 
  | 'completed' 
  | 'cancelled' 
  | 'reversed'

export interface Budget extends BaseEntity {
  name: string
  description?: string
  fiscal_year_id: string
  status: 'draft' | 'approved' | 'active' | 'closed'
  total_amount: number
  lines: BudgetLine[]
  versions: BudgetVersion[]
}

export interface BudgetLine {
  id: string
  account_id: string
  account_code: string
  account_name: string
  periods: BudgetPeriodAmount[]
  total: number
  notes?: string
}

export interface BudgetPeriodAmount {
  period_id: string
  period_name: string
  amount: number
  actual?: number
  variance?: number
  variance_percent?: number
}

export interface BudgetVersion {
  id: string
  version: number
  created_at: string
  created_by: string
  notes?: string
}

// ============================================================
// Invoice & Billing Types
// ============================================================

export interface Invoice extends BaseEntity {
  number: string
  customer_id: string
  customer?: Customer
  status: InvoiceStatus
  date: string
  due_date: string
  currency: string
  exchange_rate?: number
  lines: InvoiceLine[]
  subtotal: number
  discount_type?: 'percentage' | 'fixed'
  discount_value?: number
  discount_amount: number
  tax_amount: number
  total: number
  amount_paid: number
  amount_due: number
  payment_terms: number
  notes?: string
  terms?: string
  sent_at?: string
  viewed_at?: string
  paid_at?: string
  voided_at?: string
  void_reason?: string
  payments?: Payment[]
  attachments?: Attachment[]
}

export type InvoiceStatus = 
  | 'draft' 
  | 'sent' 
  | 'viewed' 
  | 'partial' 
  | 'paid' 
  | 'overdue' 
  | 'voided'

export interface InvoiceLine {
  id: string
  type: 'product' | 'service' | 'description'
  item_id?: string
  item_code?: string
  description: string
  quantity: number
  unit: string
  unit_price: number
  discount_percent?: number
  tax_code?: string
  tax_rate?: number
  tax_amount: number
  total: number
  account_id?: string
}

export interface Customer extends BaseEntity {
  code: string
  name: string
  type: 'individual' | 'business'
  tax_id?: string
  email: string
  phone?: string
  billing_address: Address
  shipping_address?: Address
  contact_person?: string
  payment_terms: number
  credit_limit?: number
  currency: string
  notes?: string
  is_active: boolean
  balance: number
  ar_account_id: string
}

export interface Payment extends BaseEntity {
  number: string
  type: 'payment' | 'refund' | 'credit'
  customer_id: string
  amount: number
  currency: string
  date: string
  method: PaymentMethod
  reference?: string
  treasury_account_id?: string
  status: 'pending' | 'completed' | 'cancelled'
  applied_to: PaymentApplication[]
  notes?: string
}

export type PaymentMethod = 
  | 'cash' 
  | 'check' 
  | 'ach' 
  | 'wire' 
  | 'credit_card' 
  | 'bank_transfer' 
  | 'other'

export interface PaymentApplication {
  invoice_id: string
  invoice_number: string
  amount: number
}

export interface Bill extends BaseEntity {
  number: string
  vendor_id: string
  vendor?: Vendor
  status: BillStatus
  date: string
  due_date: string
  currency: string
  exchange_rate?: number
  lines: BillLine[]
  subtotal: number
  discount_amount: number
  tax_amount: number
  total: number
  amount_paid: number
  amount_due: number
  payment_terms: number
  notes?: string
  approved_at?: string
  approved_by?: string
  paid_at?: string
  voided_at?: string
  void_reason?: string
}

export type BillStatus = 
  | 'draft' 
  | 'pending_approval' 
  | 'approved' 
  | 'partial' 
  | 'paid' 
  | 'overdue' 
  | 'voided'

export interface BillLine {
  id: string
  description: string
  quantity: number
  unit_price: number
  tax_rate?: number
  tax_amount: number
  total: number
  account_id: string
  account_code: string
  account_name: string
}

export interface Vendor extends BaseEntity {
  code: string
  name: string
  type: 'individual' | 'business'
  tax_id?: string
  email?: string
  phone?: string
  address: Address
  contact_person?: string
  payment_terms: number
  currency: string
  bank_info?: BankInfo
  notes?: string
  is_active: boolean
  balance: number
  ap_account_id: string
}

export interface BankInfo {
  bank_name: string
  account_name: string
  account_number: string
  routing_number: string
  swift_code?: string
}

// ============================================================
// HR Types
// ============================================================

export interface Employee extends BaseEntity {
  employee_number: string
  user_id?: string
  first_name: string
  last_name: string
  email: string
  phone?: string
  department_id: string
  position_id: string
  manager_id?: string
  hire_date: string
  termination_date?: string
  status: EmployeeStatus
  type: 'full_time' | 'part_time' | 'contractor' | 'temporary'
  compensation: Compensation
  address: Address
  emergency_contact?: EmergencyContact
  documents?: EmployeeDocument[]
  skills?: string[]
  certifications?: Certification[]
  benefits: BenefitEnrollment[]
}

export type EmployeeStatus = 
  | 'active' 
  | 'on_leave' 
  | 'suspended' 
  | 'terminated'

export interface Compensation {
  type: 'salary' | 'hourly'
  amount: number
  currency: string
  pay_frequency: 'weekly' | 'bi_weekly' | 'semi_monthly' | 'monthly'
  effective_date: string
  history: CompensationHistory[]
}

export interface CompensationHistory {
  effective_date: string
  previous_amount: number
  new_amount: number
  reason: string
}

export interface EmergencyContact {
  name: string
  relationship: string
  phone: string
  email?: string
}

export interface EmployeeDocument {
  id: string
  type: string
  name: string
  file_url: string
  uploaded_at: string
  expires_at?: string
}

export interface Certification {
  name: string
  issuer: string
  date_obtained: string
  expiration_date?: string
  certificate_number?: string
}

export interface BenefitEnrollment {
  benefit_id: string
  benefit_name: string
  coverage: string
  employee_cost: number
  employer_cost: number
  start_date: string
  end_date?: string
}

export interface Department extends BaseEntity {
  code: string
  name: string
  description?: string
  parent_id?: string
  manager_id?: string
  budget?: number
  cost_center?: string
  location?: string
  children?: Department[]
}

export interface Position extends BaseEntity {
  code: string
  title: string
  description?: string
  department_id: string
  level: number
  salary_range_min?: number
  salary_range_max?: number
  salary_range_mid?: number
  reports_to?: string
  is_active: boolean
}

export interface PayrollRun extends BaseEntity {
  number: string
  period_start: string
  period_end: string
  pay_date: string
  status: 'draft' | 'pending' | 'approved' | 'processed' | 'cancelled'
  total_gross: number
  total_net: number
  total_taxes: number
  total_deductions: number
  employee_count: number
  payslips: Payslip[]
  approved_at?: string
  approved_by?: string
}

export interface Payslip {
  id: string
  employee_id: string
  employee_name: string
  pay_period_start: string
  pay_period_end: string
  gross_pay: number
  net_pay: number
  taxes: PayrollLine[]
  deductions: PayrollLine[]
  earnings: PayrollLine[]
  direct_deposit?: DirectDeposit
}

export interface PayrollLine {
  code: string
  name: string
  amount: number
  ytd_amount: number
  type: 'earning' | 'deduction' | 'tax'
}

export interface DirectDeposit {
  bank_name: string
  account_type: 'checking' | 'savings'
  account_number_last4: string
  amount: number
}

export interface AttendanceRecord extends BaseEntity {
  employee_id: string
  date: string
  clock_in?: string
  clock_out?: string
  break_minutes: number
  regular_hours: number
  overtime_hours: number
  total_hours: number
  status: 'present' | 'absent' | 'late' | 'early_departure' | 'half_day' | 'holiday' | 'weekend'
  notes?: string
  location?: string
  approved_by?: string
  adjusted?: boolean
  adjustment_reason?: string
}

export interface LeaveRequest extends BaseEntity {
  employee_id: string
  leave_type_id: string
  start_date: string
  end_date: string
  days: number
  reason?: string
  status: 'pending' | 'approved' | 'rejected' | 'cancelled'
  approved_by?: string
  approved_at?: string
  rejection_reason?: string
  attachments?: Attachment[]
}

export interface LeaveType extends BaseEntity {
  code: string
  name: string
  description?: string
  accrual_rate: number
  accrual_frequency: 'daily' | 'weekly' | 'bi_weekly' | 'monthly' | 'yearly'
  max_accrual?: number
  carryover_limit?: number
  is_paid: boolean
  requires_approval: boolean
  color: string
}

// ============================================================
// Tax Types
// ============================================================

export interface TaxRate extends BaseEntity {
  code: string
  name: string
  type: 'sales' | 'purchase' | 'withholding' | 'vat' | 'gst'
  rate: number
  jurisdiction_id: string
  effective_from: string
  effective_to?: string
  is_compound: boolean
  account_id: string
  description?: string
  status: 'active' | 'inactive'
}

export interface TaxJurisdiction extends BaseEntity {
  code: string
  name: string
  type: 'federal' | 'state' | 'county' | 'city' | 'special'
  parent_id?: string
  country: string
  region?: string
}

export interface TaxNexus extends BaseEntity {
  jurisdiction_id: string
  effective_from: string
  effective_to?: string
  registration_number?: string
  filing_frequency: 'monthly' | 'quarterly' | 'annually'
  status: 'active' | 'inactive'
}

export interface TaxFiling extends BaseEntity {
  jurisdiction_id: string
  period_start: string
  period_end: string
  due_date: string
  status: 'draft' | 'pending' | 'filed' | 'paid'
  taxable_amount: number
  tax_amount: number
  adjustments: number
  total_due: number
  filed_at?: string
  filed_by?: string
  paid_at?: string
  payment_reference?: string
  notes?: string
}

// ============================================================
// Workflow Types
// ============================================================

export interface WorkflowDefinition extends BaseEntity {
  code: string
  name: string
  description?: string
  category: string
  version: number
  status: 'draft' | 'published' | 'archived'
  trigger_type: WorkflowTriggerType
  trigger_config: Record<string, unknown>
  steps: WorkflowStep[]
  variables: WorkflowVariable[]
  timeout_minutes?: number
  max_retries: number
  failure_action: 'stop' | 'continue' | 'notify'
  created_by: string
  published_at?: string
  published_by?: string
}

export type WorkflowTriggerType = 
  | 'manual' 
  | 'scheduled' 
  | 'event' 
  | 'webhook' 
  | 'approval'

export interface WorkflowStep {
  id: string
  name: string
  type: WorkflowStepType
  description?: string
  config: Record<string, unknown>
  conditions?: WorkflowCondition[]
  timeout_minutes?: number
  retry_count?: number
  error_handler?: WorkflowErrorHandler
  next_step_id?: string
  position: { x: number; y: number }
}

export type WorkflowStepType = 
  | 'approval' 
  | 'notification' 
  | 'condition' 
  | 'action' 
  | 'webhook' 
  | 'delay' 
  | 'parallel' 
  | 'subprocess'

export interface WorkflowCondition {
  field: string
  operator: 'equals' | 'not_equals' | 'contains' | 'greater_than' | 'less_than' | 'is_empty' | 'is_not_empty'
  value: unknown
  next_step_id: string
}

export interface WorkflowVariable {
  name: string
  type: 'string' | 'number' | 'boolean' | 'date' | 'object' | 'array'
  required: boolean
  default_value?: unknown
  description?: string
}

export interface WorkflowErrorHandler {
  type: 'retry' | 'skip' | 'notify' | 'stop'
  max_retries?: number
  retry_delay_seconds?: number
  notification_recipients?: string[]
}

export interface WorkflowExecution extends BaseEntity {
  definition_id: string
  definition_version: number
  status: WorkflowExecutionStatus
  trigger_type: string
  triggered_by: string
  started_at: string
  completed_at?: string
  current_step_id?: string
  variables: Record<string, unknown>
  tasks: WorkflowTask[]
  error?: WorkflowError
  parent_execution_id?: string
}

export type WorkflowExecutionStatus = 
  | 'pending' 
  | 'running' 
  | 'paused' 
  | 'completed' 
  | 'failed' 
  | 'cancelled'

export interface WorkflowTask {
  id: string
  step_id: string
  step_name: string
  type: string
  status: 'pending' | 'running' | 'completed' | 'failed' | 'skipped'
  assigned_to?: string
  assigned_group?: string
  started_at?: string
  completed_at?: string
  result?: Record<string, unknown>
  error?: string
  comments: WorkflowComment[]
}

export interface WorkflowComment {
  id: string
  user_id: string
  user_name: string
  content: string
  created_at: string
}

export interface WorkflowError {
  step_id: string
  message: string
  stack_trace?: string
  timestamp: string
}

// ============================================================
// Legal Types
// ============================================================

export interface Contract extends BaseEntity {
  number: string
  title: string
  type: ContractType
  status: ContractStatus
  counterparty_type: 'customer' | 'vendor' | 'partner' | 'employee' | 'other'
  counterparty_id: string
  counterparty_name: string
  description?: string
  value: number
  currency: string
  start_date: string
  end_date: string
  renewal_type: 'none' | 'automatic' | 'manual'
  renewal_term_days?: number
  signed_at?: string
  effective_date?: string
  termination_date?: string
  termination_reason?: string
  responsible_party_id: string
  terms?: string
  custom_fields?: Record<string, unknown>
  documents: ContractDocument[]
  amendments: ContractAmendment[]
  milestones: ContractMilestone[]
  alerts: ContractAlert[]
  created_by: string
  approved_by?: string
  approved_at?: string
}

export type ContractType = 
  | 'sales' 
  | 'purchase' 
  | 'service' 
  | 'employment' 
  | 'lease' 
  | 'license' 
  | 'partnership' 
  | 'nda' 
  | 'other'

export type ContractStatus = 
  | 'draft' 
  | 'pending_review' 
  | 'pending_approval' 
  | 'approved' 
  | 'pending_signature' 
  | 'active' 
  | 'expired' 
  | 'terminated' 
  | 'renewed'

export interface ContractDocument {
  id: string
  name: string
  type: string
  file_url: string
  file_size: number
  uploaded_at: string
  uploaded_by: string
  version: number
}

export interface ContractAmendment {
  id: string
  number: string
  description: string
  effective_date: string
  created_at: string
  created_by: string
  document_url?: string
}

export interface ContractMilestone {
  id: string
  name: string
  description?: string
  due_date: string
  completed: boolean
  completed_at?: string
  notes?: string
}

export interface ContractAlert {
  id: string
  type: 'expiration' | 'renewal' | 'milestone' | 'custom'
  trigger_date: string
  days_before?: number
  recipients: string[]
  message: string
  sent: boolean
  sent_at?: string
}

export interface LegalMatter extends BaseEntity {
  number: string
  title: string
  description: string
  type: LegalMatterType
  status: LegalMatterStatus
  priority: 'low' | 'medium' | 'high' | 'critical'
  opened_date: string
  closed_date?: string
  estimated_cost?: number
  actual_cost?: number
  currency: string
  responsible_attorney_id: string
  department_id?: string
  counterparty?: string
  case_number?: string
  court?: string
  judge?: string
  notes?: string
  tasks: LegalTask[]
  time_entries: TimeEntry[]
  documents: LegalDocument[]
}

export type LegalMatterType = 
  | 'litigation' 
  | 'regulatory' 
  | 'transactional' 
  | 'intellectual_property' 
  | 'employment' 
  | 'contract' 
  | 'compliance' 
  | 'other'

export type LegalMatterStatus = 
  | 'open' 
  | 'in_progress' 
  | 'pending_settlement' 
  | 'settled' 
  | 'closed' 
  | 'appealed'

export interface LegalTask {
  id: string
  title: string
  description?: string
  assigned_to: string
  due_date: string
  status: 'pending' | 'in_progress' | 'completed' | 'cancelled'
  priority: 'low' | 'medium' | 'high'
  completed_at?: string
}

export interface TimeEntry {
  id: string
  user_id: string
  user_name: string
  date: string
  hours: number
  rate: number
  amount: number
  description: string
  billable: boolean
  status: 'draft' | 'approved' | 'invoiced'
}

export interface LegalDocument {
  id: string
  name: string
  type: string
  file_url: string
  file_size: number
  uploaded_at: string
  uploaded_by: string
}

export interface ComplianceRequirement extends BaseEntity {
  code: string
  name: string
  description: string
  category: string
  jurisdiction: string
  frequency: 'one_time' | 'daily' | 'weekly' | 'monthly' | 'quarterly' | 'annually'
  next_due_date: string
  last_completed_date?: string
  status: 'compliant' | 'non_compliant' | 'pending' | 'overdue'
  responsible_party_id: string
  checklist: ComplianceChecklistItem[]
  documents: LegalDocument[]
  notes?: string
}

export interface ComplianceChecklistItem {
  id: string
  title: string
  description?: string
  completed: boolean
  completed_at?: string
  completed_by?: string
  due_date?: string
}

// ============================================================
// Report Types
// ============================================================

export interface ReportTemplate extends BaseEntity {
  code: string
  name: string
  description?: string
  category: string
  type: ReportType
  data_source: string
  parameters: ReportParameter[]
  columns: ReportColumn[]
  filters: ReportFilter[]
  sorting: ReportSorting[]
  grouping?: string
  charts?: ReportChart[]
  schedule?: ReportSchedule
  is_system: boolean
  created_by: string
}

export type ReportType = 
  | 'table' 
  | 'summary' 
  | 'chart' 
  | 'pivot' 
  | 'crosstab' 
  | 'financial'

export interface ReportParameter {
  name: string
  label: string
  type: 'string' | 'number' | 'date' | 'boolean' | 'select' | 'multiselect'
  required: boolean
  default_value?: unknown
  options?: SelectOption[]
  validation?: Record<string, unknown>
}

export interface ReportColumn {
  name: string
  label: string
  type: 'string' | 'number' | 'currency' | 'percent' | 'date' | 'boolean'
  format?: string
  width?: number
  alignment?: 'left' | 'center' | 'right'
  sortable: boolean
  groupable: boolean
  aggregate?: 'sum' | 'avg' | 'count' | 'min' | 'max'
}

export interface ReportFilter {
  field: string
  operator: string
  value: unknown
  label?: string
}

export interface ReportSorting {
  field: string
  direction: 'asc' | 'desc'
}

export interface ReportChart {
  type: 'bar' | 'line' | 'pie' | 'donut' | 'area' | 'scatter'
  title: string
  x_field: string
  y_fields: string[]
  options?: Record<string, unknown>
}

export interface ReportSchedule {
  frequency: 'daily' | 'weekly' | 'monthly' | 'quarterly'
  time: string
  day_of_week?: number
  day_of_month?: number
  recipients: string[]
  format: 'pdf' | 'excel' | 'csv'
  last_run?: string
  next_run?: string
  active: boolean
}

export interface ReportExecution extends BaseEntity {
  template_id: string
  parameters: Record<string, unknown>
  status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled'
  started_at: string
  completed_at?: string
  row_count?: number
  file_url?: string
  file_size?: number
  error?: string
  created_by: string
}

export interface Dashboard extends BaseEntity {
  name: string
  description?: string
  layout: DashboardLayout
  widgets: DashboardWidget[]
  filters: DashboardFilter[]
  is_default: boolean
  is_shared: boolean
  shared_with: string[]
  created_by: string
}

export interface DashboardLayout {
  columns: number
  row_height: number
  gap: number
}

export interface DashboardWidget {
  id: string
  type: DashboardWidgetType
  title: string
  config: Record<string, unknown>
  position: {
    x: number
    y: number
    w: number
    h: number
  }
  data_source?: string
  refresh_interval?: number
}

export type DashboardWidgetType = 
  | 'kpi' 
  | 'chart' 
  | 'table' 
  | 'gauge' 
  | 'map' 
  | 'list' 
  | 'text' 
  | 'iframe'

export interface DashboardFilter {
  name: string
  label: string
  type: 'date_range' | 'select' | 'multiselect' | 'number'
  default_value?: unknown
  applies_to: string[]
}

// ============================================================
// Consolidation Types
// ============================================================

export interface ConsolidationScenario extends BaseEntity {
  name: string
  description?: string
  type: 'actual' | 'budget' | 'forecast'
  period_type: 'monthly' | 'quarterly' | 'yearly'
  start_period: string
  end_period: string
  base_currency: string
  status: 'draft' | 'pending' | 'running' | 'completed' | 'failed'
  companies: ConsolidationCompany[]
  elimination_rules: EliminationRule[]
  intercompany_transactions: IntercompanyTransaction[]
  results?: ConsolidationResult
  created_by: string
  completed_at?: string
}

export interface ConsolidationCompany {
  company_id: string
  company_name: string
  ownership_percent: number
  consolidation_method: 'full' | 'proportional' | 'equity'
  exchange_rate_type: 'spot' | 'average' | 'historical'
  exchange_rate?: number
  local_currency: string
}

export interface EliminationRule extends BaseEntity {
  name: string
  description?: string
  type: 'intercompany' | 'adjustment' | 'reclassification'
  debit_account_id: string
  credit_account_id: string
  amount_type: 'fixed' | 'percentage' | 'calculated'
  amount?: number
  formula?: string
  matching_criteria: Record<string, unknown>
  active: boolean
}

export interface IntercompanyTransaction {
  id: string
  from_company_id: string
  to_company_id: string
  transaction_type: 'sale' | 'purchase' | 'loan' | 'dividend' | 'fee' | 'other'
  amount: number
  currency: string
  date: string
  description: string
  matched: boolean
  matched_with?: string
}

export interface ConsolidationResult {
  total_revenue: number
  total_expenses: number
  net_income: number
  total_assets: number
  total_liabilities: number
  total_equity: number
  elimination_total: number
  minority_interest?: number
  exchange_gain_loss: number
}

// ============================================================
// Asset Types
// ============================================================

export interface FixedAsset extends BaseEntity {
  asset_number: string
  name: string
  description?: string
  class_id: string
  class_name?: string
  location_id: string
  location_name?: string
  type: 'tangible' | 'intangible'
  status: AssetStatus
  acquisition_date: string
  acquisition_cost: number
  currency: string
  salvage_value: number
  useful_life_years: number
  useful_life_units?: number
  depreciation_method: DepreciationMethod
  depreciation_convention: 'full_month' | 'half_year' | 'mid_month'
  accumulated_depreciation: number
  net_book_value: number
  last_depreciation_date?: string
  dispose_date?: string
  disposal_value?: number
  responsible_person_id?: string
  serial_number?: string
  warranty_expiry?: string
  insurance_policy_id?: string
  notes?: string
  custom_fields?: Record<string, unknown>
  documents?: Attachment[]
  maintenance_records?: MaintenanceRecord[]
}

export type AssetStatus = 
  | 'pending' 
  | 'active' 
  | 'fully_depreciated' 
  | 'disposed' 
  | 'impaired' 
  | 'held_for_sale'

export type DepreciationMethod = 
  | 'straight_line' 
  | 'declining_balance' 
  | 'double_declining' 
  | 'sum_of_years' 
  | 'units_of_production'

export interface AssetClass extends BaseEntity {
  code: string
  name: string
  description?: string
  asset_type: 'tangible' | 'intangible'
  default_useful_life_years: number
  default_depreciation_method: DepreciationMethod
  depreciation_rate?: number
  asset_account_id: string
  accumulated_depreciation_account_id: string
  depreciation_expense_account_id: string
  parent_id?: string
  children?: AssetClass[]
}

export interface AssetLocation extends BaseEntity {
  code: string
  name: string
  description?: string
  address?: Address
  responsible_person_id?: string
  parent_id?: string
  children?: AssetLocation[]
}

export interface DepreciationRun extends BaseEntity {
  number: string
  period_start: string
  period_end: string
  status: 'draft' | 'posted' | 'reversed'
  total_depreciation: number
  asset_count: number
  journal_entry_id?: string
  posted_at?: string
  posted_by?: string
  details: DepreciationDetail[]
}

export interface DepreciationDetail {
  asset_id: string
  asset_number: string
  asset_name: string
  beginning_value: number
  depreciation_amount: number
  ending_value: number
  days_in_period: number
}

export interface AssetDisposal extends BaseEntity {
  number: string
  asset_id: string
  asset_number: string
  asset_name: string
  disposal_type: 'sale' | 'retirement' | 'donation' | 'trade_in' | 'loss'
  disposal_date: string
  disposal_value: number
  net_book_value: number
  gain_loss: number
  currency: string
  buyer?: string
  notes?: string
  status: 'pending' | 'approved' | 'completed'
  approved_by?: string
  approved_at?: string
}

export interface MaintenanceRecord extends BaseEntity {
  asset_id: string
  type: 'preventive' | 'corrective' | 'upgrade'
  description: string
  start_date: string
  end_date?: string
  cost: number
  currency: string
  vendor_id?: string
  vendor_name?: string
  status: 'scheduled' | 'in_progress' | 'completed' | 'cancelled'
  notes?: string
  documents?: Attachment[]
}

// ============================================================
// AI Types
// ============================================================

export interface AIModel extends BaseEntity {
  name: string
  description?: string
  type: AIModelType
  algorithm: string
  version: string
  status: 'development' | 'staging' | 'production' | 'deprecated'
  features: string[]
  parameters: Record<string, unknown>
  metrics: AIModelMetrics
  training_history: AITrainingRun[]
  created_by: string
}

export type AIModelType = 
  | 'classification' 
  | 'regression' 
  | 'forecasting' 
  | 'anomaly_detection' 
  | 'clustering' 
  | 'nlp' 
  | 'recommendation'

export interface AIModelMetrics {
  accuracy?: number
  precision?: number
  recall?: number
  f1_score?: number
  rmse?: number
  mae?: number
  r2?: number
  auc_roc?: number
}

export interface AITrainingRun {
  id: string
  started_at: string
  completed_at?: string
  status: 'pending' | 'running' | 'completed' | 'failed'
  parameters: Record<string, unknown>
  metrics?: AIModelMetrics
  error?: string
}

export interface Anomaly extends BaseEntity {
  model_id?: string
  entity_type: string
  entity_id: string
  type: 'statistical' | 'ml' | 'rule_based'
  severity: 'low' | 'medium' | 'high' | 'critical'
  score: number
  detected_at: string
  description: string
  details: Record<string, unknown>
  status: 'open' | 'confirmed' | 'dismissed' | 'resolved'
  confirmed_at?: string
  confirmed_by?: string
  dismissed_at?: string
  dismissed_by?: string
  dismissed_reason?: string
  resolved_at?: string
  resolution_notes?: string
}

export interface Forecast extends BaseEntity {
  name: string
  description?: string
  model_id: string
  entity_type: string
  forecast_type: 'point' | 'interval' | 'distribution'
  horizon_days: number
  frequency: 'daily' | 'weekly' | 'monthly'
  status: 'pending' | 'running' | 'completed' | 'failed'
  parameters: Record<string, unknown>
  results?: ForecastResult[]
  accuracy_metrics?: ForecastAccuracy
  created_by: string
  completed_at?: string
}

export interface ForecastResult {
  date: string
  value: number
  lower_bound?: number
  upper_bound?: number
  confidence_level?: number
  actual_value?: number
  error?: number
}

export interface ForecastAccuracy {
  mape?: number
  mae?: number
  rmse?: number
  bias?: number
}

export interface AIInsight extends BaseEntity {
  type: AIInsightType
  title: string
  description: string
  category: string
  priority: 'low' | 'medium' | 'high'
  impact_score: number
  confidence: number
  data: Record<string, unknown>
  recommendations?: string[]
  related_entities: { type: string; id: string; name: string }[]
  status: 'new' | 'viewed' | 'acted' | 'dismissed'
  viewed_at?: string
  acted_at?: string
  dismissed_at?: string
  created_by?: string
}

export type AIInsightType = 
  | 'trend' 
  | 'anomaly' 
  | 'opportunity' 
  | 'risk' 
  | 'recommendation' 
  | 'prediction'

export interface AIRecommendation extends BaseEntity {
  insight_id?: string
  type: string
  title: string
  description: string
  rationale: string
  expected_impact: string
  estimated_roi?: number
  effort: 'low' | 'medium' | 'high'
  priority: number
  actions: RecommendedAction[]
  status: 'pending' | 'applied' | 'dismissed'
  applied_at?: string
  applied_by?: string
  dismissed_at?: string
  dismissed_reason?: string
}

export interface RecommendedAction {
  type: string
  description: string
  parameters: Record<string, unknown>
  automated: boolean
}

export interface NLCommand extends BaseEntity {
  query: string
  intent?: string
  entities?: Record<string, unknown>
  interpretation?: string
  result?: Record<string, unknown>
  error?: string
  confidence: number
  feedback?: 'positive' | 'negative'
  user_id: string
  created_at: string
}

export interface DocumentAnalysis extends BaseEntity {
  document_type: string
  document_name: string
  status: 'pending' | 'processing' | 'completed' | 'failed'
  extracted_data?: Record<string, unknown>
  entities?: ExtractedEntity[]
  key_terms?: KeyTerm[]
  clauses?: Clause[]
  risk_score?: number
  risk_factors?: string[]
  summary?: string
  created_by: string
  completed_at?: string
}

export interface ExtractedEntity {
  type: string
  text: string
  value?: string
  confidence: number
  position: { start: number; end: number }
}

export interface KeyTerm {
  term: string
  definition?: string
  importance: number
}

export interface Clause {
  type: string
  title: string
  content: string
  position: { start: number; end: number }
  risk_level?: 'low' | 'medium' | 'high'
  summary?: string
}

// ============================================================
// Notification Types
// ============================================================

export interface Notification extends BaseEntity {
  type: NotificationType
  title: string
  message: string
  severity: 'info' | 'success' | 'warning' | 'error'
  read: boolean
  read_at?: string
  action_url?: string
  action_label?: string
  data?: Record<string, unknown>
  expires_at?: string
}

export type NotificationType = 
  | 'system' 
  | 'approval' 
  | 'mention' 
  | 'task' 
  | 'alert' 
  | 'reminder' 
  | 'workflow'
  | 'ai'

export interface NotificationPreferences {
  channels: {
    in_app: boolean
    email: boolean
    push: boolean
    sms: boolean
  }
  types: Record<NotificationType, {
    enabled: boolean
    channels: string[]
  }>
  quiet_hours: {
    enabled: boolean
    start: string
    end: string
    timezone: string
  }
  digest: {
    enabled: boolean
    frequency: 'daily' | 'weekly'
    time: string
  }
}

// ============================================================
// Attachment Types
// ============================================================

export interface Attachment {
  id: string
  name: string
  type: string
  size: number
  url: string
  uploaded_at: string
  uploaded_by: string
  thumbnail_url?: string
}

// ============================================================
// Search Types
// ============================================================

export interface SearchResult {
  id: string
  type: string
  title: string
  description?: string
  url: string
  icon?: string
  score: number
  highlights?: Record<string, string[]>
}

export interface SavedSearch extends BaseEntity {
  name: string
  query: string
  filters: Record<string, unknown>
  entity_types?: string[]
  user_id: string
}

// ============================================================
// Audit Log Types
// ============================================================

export interface AuditLogEntry {
  id: string
  timestamp: string
  user_id: string
  user_name: string
  action: string
  entity_type: string
  entity_id: string
  entity_name?: string
  changes?: {
    before?: Record<string, unknown>
    after?: Record<string, unknown>
  }
  ip_address: string
  user_agent: string
  company_id: string
  metadata?: Record<string, unknown>
}