export type ClientType = 'individual' | 'corporate'
export type ClientStatus = 'prospect' | 'conflict_check' | 'active' | 'closed' | 'rejected'

export interface RetainerTransaction {
  txId: string
  type: 'intake' | 'disbursement' | 'refund' | 'invoice_applied'
  amount: number
  currency: string
  date: string
  description: string
  matterId?: string
  invoiceRef?: string
  createdBy: string
}

export interface PhoneEntry {
  countryCode: string   // ISO 3166-1 alpha-2 e.g. "TH"
  dialCode: string      // e.g. "+66"
  number: string        // local number digits only
  type: 'mobile' | 'office' | 'whatsapp' | 'line' | 'signal' | 'fax' | 'other'
}

export interface EmailEntry {
  address: string
  type: 'primary' | 'secondary' | 'billing' | 'other'
}

export interface FolderTeamMember {
  name: string
  role: 'responsible_attorney' | 'originating_attorney' | 'associate_attorney' | 'paralegal' | 'secretary' | 'translator' | 'external_counsel' | 'other'
  firm?: string       // for external counsel
  email?: string
  phone?: string
  notes?: string
}

export interface FolderParty {
  name: string
  type: 'opposing_counsel' | 'opposing_party' | 'judge' | 'prosecutor' | 'government_counsel' | 'court_officer' | 'government_agency' | 'other'
  organization?: string   // firm, court, agency name
  role?: string           // specific role description
  email?: string
  phone?: string
  barNumber?: string      // for lawyers
  notes?: string
}

export type AgencyType = 'consulate' | 'embassy' | 'boi' | 'immigration_office' | 'ministry' | 'regulatory' | 'court' | 'municipality' | 'customs' | 'tax' | 'other'
export type EventType = 'submission' | 'appointment' | 'deadline' | 'renewal' | 'approval' | 'rejection' | 'inspection' | 'payment' | 'hearing' | 'other'
export type EventStatus = 'upcoming' | 'in_progress' | 'completed' | 'overdue' | 'cancelled'

export interface FolderAgency {
  id: string
  name: string
  agencyType: AgencyType
  country?: string
  contactPerson?: string
  phone?: string
  email?: string
  website?: string
  referenceNumber?: string  // client's ref# at this agency (visa file no., BOI app no., etc.)
  notes?: string
}

export interface ComplianceEvent {
  id: string
  title: string
  agencyId: string
  agencyName: string
  eventType: EventType
  date: string              // ISO date string
  status: EventStatus
  matterId?: string
  matterTitle?: string
  referenceNumber?: string
  notes?: string
}

export interface AddressEntry {
  line1: string
  line2?: string
  city?: string
  state?: string
  postal?: string
  country: string   // ISO 3166-1 alpha-2
  type: 'primary' | 'mailing' | 'billing' | 'home' | 'foreign' | 'other'
}

// ─── Document management ──────────────────────────────────────────────────────

export interface DocFolder {
  _id: string
  name: string
  icon: string          // remixicon class
  color: string         // hex
  isSystem: boolean     // system default vs user/AI created
  createdAt: string
  createdBy: string
}

export type DocAiStatus = 'pending' | 'processing' | 'classified' | 'failed'

export type DocType =
  | 'contract' | 'agreement' | 'court_filing' | 'pleading' | 'affidavit'
  | 'correspondence' | 'identity' | 'financial' | 'evidence' | 'deed'
  | 'power_of_attorney' | 'report' | 'opinion' | 'permit' | 'other'

export interface LegalDocument {
  _id: string
  batesNumber: string      // e.g. CLI-2025-0042-00001  — assigned at upload
  folderId: string | null  // null = Inbox (unclassified)
  fileName: string
  originalName: string
  mimeType: string
  fileSize: number         // bytes
  documentType?: DocType
  documentDate?: string    // date on the document itself
  parties?: string[]       // extracted by AI
  summary?: string         // AI-generated summary
  tags?: string[]
  matterId?: string        // linked matter if relevant
  uploadedBy: string
  uploadedAt: string
  aiStatus: DocAiStatus
  storageKey: string       // S3/object storage reference
  detectedLanguage?: string
  translatedSummary?: string
  translatedSummaryLang?: string
  isTranslation?: boolean
  translationLanguage?: string
  sourceDocumentId?: string
}

export interface ClientFolder {
  _id: string
  folderNumber: string
  clientType: ClientType

  // Individual
  firstName?: string
  lastName?: string
  nationality?: string
  passportNumber?: string
  idType?: string
  visaNumber?: string
  visaType?: string
  visaExpiry?: string
  dateOfBirth?: string

  // Corporate
  companyName?: string
  registrationNumber?: string
  boiStatus?: string
  directors?: string[]

  // Shared
  displayName: string
  email?: string
  phone?: string
  lineId?: string
  address?: string

  // Structured addresses (multi-entry)
  addresses: AddressEntry[]

  // Team & parties
  folderTeam: FolderTeamMember[]
  folderParties: FolderParty[]
  folderAgencies: FolderAgency[]
  complianceEvents: ComplianceEvent[]

  // Structured multi-contact
  phones: PhoneEntry[]
  emails: EmailEntry[]
  region?: string

  status: ClientStatus
  originatingAttorney: string
  responsibleAttorney: string

  engagementDate?: string
  engagementLetterRef?: string
  closedDate?: string
  closedReason?: string

  retainerBalance: number
  retainerThreshold: number
  currency: string
  retainerLedger: RetainerTransaction[]

  // Document management
  docFolders: DocFolder[]
  documents: LegalDocument[]
  batesCounter: number     // next Bates sequence number (server-managed)

  conflictCheckId?: string
  notes?: string
  archived: boolean
  billingConfig?: BillingConfig

  createdAt: string
  updatedAt: string
}

// ─── Matters ──────────────────────────────────────────────────────────────────

export type MatterStatus = 'open' | 'pending' | 'closed' | 'archived'
export type PracticeArea = 'immigration' | 'corporate' | 'civil_litigation' | 'property' | 'family' | 'employment' | 'criminal' | 'other'
export type BillingType = 'hourly' | 'fixed' | 'retainer' | 'contingency' | 'hybrid'

export interface Matter {
  _id: string
  matterNumber: string
  clientFolderId: string
  title: string
  practiceArea: PracticeArea
  subType?: string
  status: MatterStatus
  billingType?: BillingType
  hourlyRate?: number
  fixedFee?: number
  responsibleAttorney: string
  teamMembers: string[]
  openedDate: string
  closedDate?: string
  closedOutcome?: string
  courtReference?: string
  opposingCounsel?: string
  nextActionDate?: string
  nextActionDescription?: string
  notes?: string
  totalBilled: number
  totalPaid: number
  currency: string
  createdAt: string
  updatedAt: string
}

// ─── Time Entries ─────────────────────────────────────────────────────────────

export interface TimeEntry {
  _id: string
  matterId: string
  clientFolderId: string
  attorney: string
  date: string
  durationMinutes: number
  ratePerHour: number
  currency: string
  description: string
  taskCode?: string
  invoiceRef?: string
  billed: boolean
  createdAt: string
}

// ─── Invoices ─────────────────────────────────────────────────────────────────

export type InvoiceStatus = 'draft' | 'sent' | 'paid' | 'void'

export interface InvoiceLineItem {
  description: string
  quantity: number
  unitPrice: number
  amount: number
  timeEntryIds?: string[]
  expenseIds?: string[]
}

export interface Invoice {
  _id: string
  invoiceNumber: string
  clientFolderId: string
  matterId?: string
  lineItems: InvoiceLineItem[]
  subtotal: number
  vatRate: number
  vatAmount: number
  total: number
  currency: string
  status: InvoiceStatus
  issueDate: string
  dueDate: string
  paidDate?: string
  paidAmount?: number
  notes?: string
  createdBy: string
  createdAt: string
}

// ─── Billing Configuration ────────────────────────────────────────────────────

export type BillingFrequency = 'monthly' | 'bi_monthly' | 'quarterly' | 'upon_completion' | 'as_incurred' | 'milestone'
export type InvoiceDelivery  = 'email' | 'postal' | 'both' | 'none'

export interface RateScheduleEntry {
  attorney: string
  title?: string
  rate: number
}

export interface BillingConfig {
  // Multiple billing types — a client/matter can combine e.g. retainer + hourly
  billingTypes: BillingType[]
  /** @deprecated use billingTypes */
  billingType?: BillingType
  currency?: string
  defaultHourlyRate: number
  rateSchedule: RateScheduleEntry[]
  retainerRequired: boolean
  retainerAmount: number
  retainerThreshold: number
  autoReplenish: boolean
  billingFrequency: BillingFrequency
  billingDayOfMonth?: number
  // Manual billing schedule
  nextBillingDate?: string           // ISO date — next scheduled invoice date
  billingScheduleDates?: string[]    // specific future dates counsel has set
  paymentTermsDays: number
  vatExempt: boolean
  vatRate: number
  vatRegNumber?: string
  invoiceDelivery: InvoiceDelivery
  billingNotes?: string
  updatedBy?: string
  updatedAt?: string
}

// ─── Trust ─────────────────────────────────────────────────────────────────

export type TrustTxType =
  | 'receipt' | 'disbursement' | 'transfer_out' | 'interest'
  | 'fee_draw' | 'refund' | 'adjustment'

export interface TrustTransaction {
  _id: string
  clientFolderId: string
  matterId?: string
  txDate: string
  type: TrustTxType
  amount: number
  currency: string
  description: string
  reference?: string
  invoiceId?: string
  reconciled: boolean
  bankStatementRef?: string
  createdBy: string
  createdAt: string
}

export interface TrustAccount {
  _id: string
  clientFolderId: string
  currency: string
  bookBalance: number
  bankBalance: number
  lastReconciledDate?: string
  lastReconciledBy?: string
  isReconciled: boolean
  accountNumber?: string
  notes?: string
}

// ─── Expense ───────────────────────────────────────────────────────────────

export type ExpenseCategory =
  | 'court_filing' | 'translation' | 'notarization' | 'travel' | 'accommodation'
  | 'courier' | 'printing' | 'government_fee' | 'expert_witness' | 'other'

export type ExpenseStatus = 'pending' | 'billed' | 'reimbursed' | 'written_off'

export interface Expense {
  _id: string
  clientFolderId: string
  matterId?: string
  description: string
  category: ExpenseCategory
  amount: number
  currency: string
  expenseDate: string
  billable: boolean
  vatIncluded: boolean
  vatRate: number
  status: ExpenseStatus
  invoiceId?: string
  receiptUrl?: string
  notes?: string
  createdBy: string
  createdAt: string
}

export interface CreateClientFolderDto {
  clientType: ClientType
  firstName?: string
  lastName?: string
  nationality?: string
  passportNumber?: string
  idType?: string
  visaNumber?: string
  visaType?: string
  visaExpiry?: string
  dateOfBirth?: string
  companyName?: string
  registrationNumber?: string
  boiStatus?: string
  email?: string
  phone?: string
  lineId?: string
  address?: string
  addresses?: AddressEntry[]
  phones?: PhoneEntry[]
  emails?: EmailEntry[]
  region?: string
  originatingAttorney: string
  responsibleAttorney: string
  retainerThreshold?: number
  currency?: string
  notes?: string
}

export type UpdateClientFolderDto = Partial<CreateClientFolderDto>

// ─── Email ────────────────────────────────────────────────────────────────────

export type EmailDirection   = 'inbound' | 'outbound'
export type EmailAssocStatus = 'auto_matched' | 'confirmed' | 'pending_review' | 'unassociated'

export interface EmailAddress {
  address: string
  name?: string
}

export interface EmailAttachment {
  filename: string
  contentType: string
  size: number
  storageKey?: string
}

export interface AssociationCandidate {
  clientFolderId: string
  displayName: string
  folderNumber: string
  matterId?: string
  matterNumber?: string
  matterTitle?: string
  confidence: number
  reason: string
}

export interface Email {
  _id: string
  messageId: string
  threadId: string
  inReplyTo?: string
  references: string[]
  direction: EmailDirection
  from: EmailAddress
  to: EmailAddress[]
  cc: EmailAddress[]
  bcc: EmailAddress[]
  subject: string
  bodyText?: string
  bodyHtml?: string
  attachments: EmailAttachment[]
  receivedAt: string
  clientFolderId?: string
  matterId?: string
  associationStatus: EmailAssocStatus
  associationConfirmedBy?: string
  associationCandidates: AssociationCandidate[]
  forwardedBy?: string
  isRead: boolean
  isArchived: boolean
  tags: string[]
  createdAt: string
}

export interface UserEmailAccount {
  _id: string
  emailAddress: string
  displayName: string
  isActive: boolean
  notes?: string
  createdAt: string
}
