// ============================================================
//  CRM – Zentrale TypeScript-Interfaces
// ============================================================

// --- Enums ---

export type ContactType = 'PERSON' | 'ORGANIZATION';
export type DealStatus = 'OPEN' | 'WON' | 'LOST';
export type ActivityType = 'NOTE' | 'CALL' | 'EMAIL' | 'MEETING' | 'TASK' | 'FOLLOWUP';
export type ContractStatus = 'DRAFT' | 'ACTIVE' | 'EXPIRED' | 'CANCELLED';

// Phase 1 Enums
export type ContactSource = 'TRADE_FAIR' | 'REFERRAL' | 'WEBSITE' | 'COLD_CALL' | 'IMPORT' | 'BUSINESS_CARD' | 'OTHER';
export type EntityStatus = 'ACTIVE' | 'INACTIVE' | 'BLOCKED';
export type CompanySize = 'SIZE_1_10' | 'SIZE_11_50' | 'SIZE_51_200' | 'SIZE_201_500' | 'SIZE_500_PLUS';
export type OwnerRole = 'OWNER' | 'MEMBER' | 'WATCHER';
export type LostReason = 'PRICE' | 'TIMING' | 'COMPETITOR' | 'NO_NEED' | 'OTHER';
export type EmailType = 'WORK' | 'PERSONAL' | 'OTHER';
export type PhoneType = 'OFFICE' | 'MOBILE' | 'FAX';

// Label-Maps fuer UI
export const CONTACT_SOURCE_LABELS: Record<ContactSource, string> = {
  TRADE_FAIR: 'Messe',
  REFERRAL: 'Empfehlung',
  WEBSITE: 'Website',
  COLD_CALL: 'Kaltakquise',
  IMPORT: 'Import',
  BUSINESS_CARD: 'Visitenkarte',
  OTHER: 'Sonstige',
};

export const ENTITY_STATUS_LABELS: Record<EntityStatus, string> = {
  ACTIVE: 'Aktiv',
  INACTIVE: 'Inaktiv',
  BLOCKED: 'Gesperrt',
};

export const COMPANY_SIZE_LABELS: Record<CompanySize, string> = {
  SIZE_1_10: '1–10',
  SIZE_11_50: '11–50',
  SIZE_51_200: '51–200',
  SIZE_201_500: '201–500',
  SIZE_500_PLUS: '500+',
};

export const OWNER_ROLE_LABELS: Record<OwnerRole, string> = {
  OWNER: 'Verantwortlich',
  MEMBER: 'Mitarbeiter',
  WATCHER: 'Beobachter',
};

export const LOST_REASON_LABELS: Record<LostReason, string> = {
  PRICE: 'Preis',
  TIMING: 'Timing',
  COMPETITOR: 'Wettbewerber',
  NO_NEED: 'Kein Bedarf',
  OTHER: 'Sonstiges',
};

export const EMAIL_TYPE_LABELS: Record<EmailType, string> = {
  WORK: 'Arbeit',
  PERSONAL: 'Privat',
  OTHER: 'Sonstige',
};

export const PHONE_TYPE_LABELS: Record<PhoneType, string> = {
  OFFICE: 'Buero',
  MOBILE: 'Mobil',
  FAX: 'Fax',
};

// --- Multi-Value Contact Info ---

export interface ContactEmail {
  id: string;
  email: string;
  type: EmailType;
  isPrimary: boolean;
  createdAt: string;
}

export interface ContactPhone {
  id: string;
  phone: string;
  type: PhoneType;
  isPrimary: boolean;
  createdAt: string;
}

export interface CreateEmailPayload {
  email: string;
  type?: EmailType;
  isPrimary?: boolean;
}

export interface CreatePhonePayload {
  phone: string;
  type?: PhoneType;
  isPrimary?: boolean;
}

// --- Owner (m:n) ---

export interface EntityOwner {
  id: string;
  tenantId: string;
  userId: string;
  role: OwnerRole;
  createdAt: string;
}

export interface AddOwnerPayload {
  userId: string;
  role?: OwnerRole;
}

// --- Admin-konfigurierbare Entitaeten ---

export interface Industry {
  id: string;
  tenantId: string;
  name: string;
  color: string;
  sortOrder: number;
  createdAt: string;
  updatedAt: string;
  _count?: { companies: number };
}

export interface AccountType {
  id: string;
  tenantId: string;
  name: string;
  sortOrder: number;
  createdAt: string;
  updatedAt: string;
  _count?: { companies: number };
}

export interface RelationshipType {
  id: string;
  tenantId: string;
  name: string;
  sortOrder: number;
  createdAt: string;
  updatedAt: string;
  _count?: { relationships: number };
}

export interface DealType {
  id: string;
  tenantId: string;
  name: string;
  color: string;
  sortOrder: number;
  isProjectType: boolean;
  createdAt: string;
  updatedAt: string;
  _count?: { deals: number };
}

export interface CreateDealTypePayload {
  name: string;
  color?: string;
  sortOrder?: number;
  isProjectType?: boolean;
}

export type UpdateDealTypePayload = Partial<CreateDealTypePayload>;

// --- ProjectRequestDetails ---

export interface ProjectRequestDetails {
  id: string;
  dealId: string;
  notes: string | null;
  workload: string | null;       // Decimal kommt als String vom Backend
  startDate: string | null;
  duration: string | null;
  onsitePercent: string | null;  // Decimal als String
  rateRemote: string | null;     // Decimal als String
  rateOnsite: string | null;     // Decimal als String
  createdAt: string;
  updatedAt: string;
}

export interface CreateProjectRequestPayload {
  notes?: string;
  workload?: number;
  startDate?: string;
  duration?: string;
  onsitePercent?: number;
  rateRemote?: number;
  rateOnsite?: number;
}

export interface CompanyRelationship {
  id: string;
  tenantId: string;
  companyId: string;
  relatedCompanyId: string;
  relationshipTypeId: string;
  notes: string | null;
  createdBy: string;
  createdAt: string;
  relatedCompany: {
    id: string;
    name: string;
    industry: string | null;
    city: string | null;
  };
  relationshipType: {
    id: string;
    name: string;
  };
  direction?: 'outgoing' | 'incoming';
}

export interface Contract {
  id: string;
  tenantId: string;
  companyId: string;
  title: string;
  status: ContractStatus;
  startDate: string | null;
  endDate: string | null;
  value: string | null;
  currency: string;
  notes: string | null;
  createdBy: string;
  createdAt: string;
  updatedAt: string;
}

export interface ContractFile {
  id: string;
  contractId: string;
  originalName: string;
  mimeType: string;
  size: number;
  uploadedBy: string;
  createdAt: string;
}

export interface CreateContractPayload {
  title: string;
  status?: ContractStatus;
  startDate?: string | null;
  endDate?: string | null;
  value?: string | null;
  currency?: string;
  notes?: string | null;
}

export type UpdateContractPayload = Partial<CreateContractPayload>;

export interface ContractsQueryParams {
  status?: ContractStatus;
  search?: string;
  sort?: string;
  order?: 'asc' | 'desc';
  page?: number;
  pageSize?: number;
}

export interface TenantUser {
  id: string;
  firstName: string | null;
  lastName: string | null;
  email: string;
}

export interface CreateIndustryPayload {
  name: string;
  color?: string;
  sortOrder?: number;
}

export type UpdateIndustryPayload = Partial<CreateIndustryPayload>;

export interface CreateAccountTypePayload {
  name: string;
  sortOrder?: number;
}

export type UpdateAccountTypePayload = Partial<CreateAccountTypePayload>;

export interface CreateRelationshipTypePayload {
  name: string;
  sortOrder?: number;
}

export type UpdateRelationshipTypePayload = Partial<CreateRelationshipTypePayload>;

export interface CreateCompanyRelationshipPayload {
  relatedCompanyId: string;
  relationshipTypeId: string;
  notes?: string;
}

// --- Contact ---

export interface Contact {
  id: string;
  tenantId: string;
  type: ContactType;
  companyId: string | null;
  position: string | null;
  firstName: string | null;
  lastName: string | null;
  companyName: string | null;
  email: string | null;
  phone: string | null;
  mobile: string | null;
  website: string | null;
  linkedinUrl: string | null;
  birthday: string | null;
  source: ContactSource | null;
  department: string | null;
  street: string | null;
  zip: string | null;
  city: string | null;
  state: string | null;
  country: string;
  notes: string | null;
  tags: string[];
  status: EntityStatus;
  isActive: boolean; // deprecated — use status
  createdBy: string;
  updatedBy: string | null;
  createdAt: string;
  updatedAt: string;
  lexwareContactId: string | null;
  lexwareContactVersion: number | null;
  lexwareSyncedAt: string | null;
  emails?: ContactEmail[];
  phones?: ContactPhone[];
  owners?: EntityOwner[];
  activities?: Activity[];
  customFields?: CustomFieldValue[];
  company?: {
    id: string;
    name: string;
    industry: string | null;
    city?: string | null;
    website?: string | null;
  } | null;
}

export interface CreateContactPayload {
  type?: ContactType;
  companyId?: string;
  position?: string;
  firstName?: string;
  lastName?: string;
  companyName?: string;
  email?: string;
  phone?: string;
  mobile?: string;
  website?: string;
  linkedinUrl?: string;
  birthday?: string;
  source?: ContactSource;
  department?: string;
  street?: string;
  zip?: string;
  city?: string;
  state?: string;
  country?: string;
  notes?: string;
  tags?: string[];
  status?: EntityStatus;
  isActive?: boolean; // deprecated
  emails?: CreateEmailPayload[];
  phones?: CreatePhonePayload[];
}

export type UpdateContactPayload = Partial<CreateContactPayload>;

// --- Activity ---

export interface Activity {
  id: string;
  tenantId: string;
  contactId: string | null;
  companyId: string | null;
  type: ActivityType;
  subject: string;
  description: string | null;
  scheduledAt: string | null;
  completedAt: string | null;
  createdBy: string;
  updatedBy: string | null;
  createdAt: string;
  updatedAt: string;
  contact?: {
    id: string;
    firstName: string | null;
    lastName: string | null;
    companyName: string | null;
  } | null;
  company?: {
    id: string;
    name: string;
  } | null;
}

export interface CreateActivityPayload {
  contactId?: string;
  companyId?: string;
  type: ActivityType;
  subject: string;
  description?: string;
  scheduledAt?: string;
  completedAt?: string;
}

export type UpdateActivityPayload = Partial<Omit<CreateActivityPayload, 'contactId' | 'companyId'>>;

// --- Pipeline + Stage ---

export interface PipelineStage {
  id: string;
  pipelineId: string;
  name: string;
  sortOrder: number;
  color: string;
  probability: number;
  createdAt: string;
  updatedAt: string;
}

export interface Pipeline {
  id: string;
  tenantId: string;
  name: string;
  isDefault: boolean;
  isActive: boolean;
  createdBy: string;
  updatedBy: string | null;
  createdAt: string;
  updatedAt: string;
  stages: PipelineStage[];
}

export interface CreatePipelinePayload {
  name: string;
  isDefault?: boolean;
  stages?: { name: string; sortOrder?: number; color?: string }[];
}

export interface UpdatePipelinePayload {
  name?: string;
  isDefault?: boolean;
  isActive?: boolean;
}

export interface UpdateStagePayload {
  name?: string;
  sortOrder?: number;
  color?: string;
  probability?: number;
}

export interface CreateStagePayload {
  name: string;
  sortOrder?: number;
  color?: string;
  probability?: number;
}

// --- Deal ---

export interface Deal {
  id: string;
  tenantId: string;
  pipelineId: string;
  stageId: string;
  contactId: string | null;
  companyId: string | null;
  title: string;
  value: string | null; // Decimal kommt als String vom Backend
  currency: string;
  status: DealStatus;
  expectedCloseDate: string | null;
  closedAt: string | null;
  dealTypeId: string | null;
  lostReason: LostReason | null;
  lostReasonText: string | null;
  notes: string | null;
  createdBy: string;
  updatedBy: string | null;
  createdAt: string;
  updatedAt: string;
  owners?: EntityOwner[];
  customFields?: CustomFieldValue[];
  pipeline?: { id: string; name: string; stages?: PipelineStage[] };
  stage?: { id: string; name: string; color: string };
  dealType?: { id: string; name: string; color: string; isProjectType: boolean } | null;
  contact?: {
    id: string;
    firstName: string | null;
    lastName: string | null;
    companyName: string | null;
  } | null;
  company?: { id: string; name: string } | null;
  dealVouchers?: DealVoucher[];
  projectRequest?: ProjectRequestDetails | null;
}

export interface CreateDealPayload {
  pipelineId: string;
  stageId: string;
  contactId?: string;
  companyId?: string;
  title: string;
  value?: number;
  currency?: string;
  status?: DealStatus;
  expectedCloseDate?: string;
  notes?: string;
  lostReason?: LostReason;
  lostReasonText?: string;
  dealTypeId?: string;
  projectRequest?: CreateProjectRequestPayload;
}

export type UpdateDealPayload = Partial<CreateDealPayload>;

// --- Company ---

export interface Company {
  id: string;
  tenantId: string;
  name: string;
  industry: string | null;
  industryId: string | null;
  accountTypeId: string | null;
  ownerId: string | null;
  ownerName: string | null;
  vatId: string | null;
  taxId: string | null;
  tradeRegisterNumber: string | null;
  registerCourt: string | null;
  companySize: CompanySize | null;
  email: string | null;
  phone: string | null;
  website: string | null;
  street: string | null;
  zip: string | null;
  city: string | null;
  state: string | null;
  country: string;
  deliveryStreet: string | null;
  deliveryZip: string | null;
  deliveryCity: string | null;
  deliveryCountry: string | null;
  dataEnrichedAt: string | null;
  dataEnrichedSource: string | null;
  notes: string | null;
  tags: string[];
  status: EntityStatus;
  isActive: boolean; // deprecated — use status
  createdBy: string;
  updatedBy: string | null;
  createdAt: string;
  updatedAt: string;
  lexwareContactId: string | null;
  lexwareContactVersion: number | null;
  lexwareSyncedAt: string | null;
  emails?: ContactEmail[];
  phones?: ContactPhone[];
  owners?: EntityOwner[];
  customFields?: CustomFieldValue[];
  industryRef?: Industry | null;
  accountType?: AccountType | null;
  _count?: { contacts: number; deals: number; lexwareVouchers?: number; contracts?: number };
  contacts?: {
    id: string;
    firstName: string | null;
    lastName: string | null;
    email: string | null;
    phone: string | null;
    position: string | null;
    status: EntityStatus;
    isActive: boolean;
  }[];
  deals?: Deal[];
  relationships?: CompanyRelationship[];
  relatedRelationships?: CompanyRelationship[];
  contracts?: Contract[];
}

export interface CreateCompanyPayload {
  name: string;
  industry?: string;
  industryId?: string;
  accountTypeId?: string;
  ownerId?: string;
  ownerName?: string;
  vatId?: string;
  taxId?: string;
  tradeRegisterNumber?: string;
  registerCourt?: string;
  companySize?: CompanySize;
  email?: string;
  phone?: string;
  website?: string;
  street?: string;
  zip?: string;
  city?: string;
  state?: string;
  country?: string;
  deliveryStreet?: string;
  deliveryZip?: string;
  deliveryCity?: string;
  deliveryCountry?: string;
  notes?: string;
  tags?: string[];
  status?: EntityStatus;
  isActive?: boolean; // deprecated
  emails?: CreateEmailPayload[];
  phones?: CreatePhonePayload[];
}

export type UpdateCompanyPayload = Partial<CreateCompanyPayload>;

// --- API Response Wrapper ---

export interface PaginationMeta {
  page: number;
  pageSize: number;
  total: number;
  totalPages: number;
}

export interface PaginatedResponse<T> {
  success: boolean;
  data: T[];
  pagination: PaginationMeta;
  meta: { timestamp: string };
}

export interface SingleResponse<T> {
  success: boolean;
  data: T;
  meta: { timestamp: string };
}

// --- Query Params ---

export interface ContactsQueryParams {
  page?: number;
  pageSize?: number;
  search?: string;
  type?: ContactType;
  companyId?: string;
  status?: EntityStatus;
  sort?: string;
  order?: 'asc' | 'desc';
}

export interface DealsQueryParams {
  page?: number;
  pageSize?: number;
  pipelineId?: string;
  stageId?: string;
  contactId?: string;
  companyId?: string;
  status?: DealStatus;
  search?: string;
  sort?: string;
  order?: 'asc' | 'desc';
}

export interface ActivitiesQueryParams {
  page?: number;
  pageSize?: number;
  contactId?: string;
  companyId?: string;
  includeContacts?: boolean;
  type?: ActivityType;
  sort?: string;
  order?: 'asc' | 'desc';
}

export interface CompaniesQueryParams {
  page?: number;
  pageSize?: number;
  search?: string;
  industry?: string;
  status?: EntityStatus;
  sort?: string;
  order?: 'asc' | 'desc';
}

// --- Lexware Office Integration ---

export type VoucherType =
  | 'QUOTATION'
  | 'ORDER_CONFIRMATION'
  | 'INVOICE'
  | 'CREDIT_NOTE';

export const VOUCHER_TYPE_LABELS: Record<VoucherType, string> = {
  QUOTATION: 'Angebot',
  ORDER_CONFIRMATION: 'Auftragsbestätigung',
  INVOICE: 'Rechnung',
  CREDIT_NOTE: 'Gutschrift',
};

export interface LexwareVoucher {
  id: string;
  voucherType: VoucherType;
  voucherNumber: string | null;
  voucherDate: string | null;
  voucherStatus: string | null;
  totalGrossAmount: string | null;
  totalNetAmount: string | null;
  totalTaxAmount: string | null;
  currency: string;
  title: string | null;
  lineItemsCount: number | null;
  lineItemsJson: string | null;
  lexwareDeepLink: string | null;
  fetchedAt: string;
}

export interface DealVoucher {
  id: string;
  linkedAt: string;
  voucher: LexwareVoucher;
}

export interface LexwareContactPersonEntry {
  salutation?: string;
  firstName?: string;
  lastName?: string;
  primary?: boolean;
  emailAddress?: string;
  phoneNumber?: string;
}

export interface LexwareContact {
  id: string;
  version: number;
  roles: { customer?: Record<string, unknown>; vendor?: Record<string, unknown> };
  company?: {
    name?: string;
    taxId?: string;
    allowTaxFreeInvoices?: boolean;
    contactPersons?: LexwareContactPersonEntry[];
  };
  person?: { firstName?: string; lastName?: string; salutation?: string };
  addresses?: {
    billing?: { street?: string; zip?: string; city?: string; countryCode?: string }[];
    shipping?: { street?: string; zip?: string; city?: string; countryCode?: string }[];
  };
  emailAddresses?: { business?: string[]; office?: string[]; private?: string[]; other?: string[] };
  phoneNumbers?: { business?: string[]; office?: string[]; mobile?: string[]; private?: string[]; fax?: string[] };
  note?: string;
  archived?: boolean;
}

export interface LexwareContactSearchParams {
  name?: string;
  email?: string;
  customer?: boolean;
  vendor?: boolean;
  page?: number;
  size?: number;
}

export interface LexwareVouchersQueryParams {
  voucherType?: VoucherType;
  voucherStatus?: string;
  page?: number;
  pageSize?: number;
}

// ============================================================
//  Trade Events (Messe-Timer)
// ============================================================

export interface TradeEvent {
  id: string;
  tenantId: string;
  name: string;
  description: string | null;
  startDate: string;
  endDate: string;
  location: string | null;
  boothInfo: string | null;
  websiteUrl: string | null;
  isActive: boolean;
  sortOrder: number;
  createdBy: string;
  updatedBy: string | null;
  createdAt: string;
  updatedAt: string;
}

export interface CreateTradeEventPayload {
  name: string;
  description?: string;
  startDate: string;
  endDate: string;
  location?: string;
  boothInfo?: string;
  websiteUrl?: string;
  isActive?: boolean;
  sortOrder?: number;
}

export interface UpdateTradeEventPayload {
  name?: string;
  description?: string;
  startDate?: string;
  endDate?: string;
  location?: string;
  boothInfo?: string;
  websiteUrl?: string;
  isActive?: boolean;
  sortOrder?: number;
}

// ============================================================
//  Custom Fields (Phase 2.1)
// ============================================================

export type CustomFieldEntityType = 'PERSON' | 'COMPANY' | 'DEAL';
export type CustomFieldType =
  | 'TEXT'
  | 'TEXTAREA'
  | 'NUMBER'
  | 'DATE'
  | 'DROPDOWN'
  | 'MULTI_SELECT'
  | 'CHECKBOX'
  | 'URL';

export const CUSTOM_FIELD_ENTITY_TYPE_LABELS: Record<CustomFieldEntityType, string> = {
  PERSON: 'Kontakte',
  COMPANY: 'Unternehmen',
  DEAL: 'Vorgaenge',
};

export const CUSTOM_FIELD_TYPE_LABELS: Record<CustomFieldType, string> = {
  TEXT: 'Text',
  TEXTAREA: 'Textbereich',
  NUMBER: 'Zahl',
  DATE: 'Datum',
  DROPDOWN: 'Dropdown',
  MULTI_SELECT: 'Mehrfachauswahl',
  CHECKBOX: 'Checkbox',
  URL: 'URL',
};

export interface CustomFieldOption {
  value: string;
  label: string;
}

export interface CustomFieldDef {
  id: string;
  tenantId: string;
  entityType: CustomFieldEntityType;
  name: string;
  label: string;
  fieldType: CustomFieldType;
  options: CustomFieldOption[] | null;
  isRequired: boolean;
  position: number;
  createdAt: string;
  updatedAt: string;
}

export interface CustomFieldValue {
  fieldDefId: string;
  name: string;
  label: string;
  fieldType: CustomFieldType;
  value: string | number | boolean | string[] | null;
}

export interface CreateCustomFieldDefPayload {
  entityType: CustomFieldEntityType;
  label: string;
  fieldType: CustomFieldType;
  options?: CustomFieldOption[];
  isRequired?: boolean;
  position?: number;
}

export interface UpdateCustomFieldDefPayload {
  label?: string;
  options?: CustomFieldOption[];
  isRequired?: boolean;
  position?: number;
}

export interface SetCustomFieldValuesPayload {
  values: Array<{
    fieldDefId: string;
    value: string | number | boolean | string[] | null;
  }>;
}

// --- Forecast ---

export interface ForecastStage {
  stageId: string;
  stageName: string;
  probability: number;
  dealCount: number;
  totalValue: number;
  weightedValue: number;
}

export interface ForecastTotals {
  dealCount: number;
  totalValue: number;
  weightedValue: number;
}

export type ForecastPeriod = 'month' | 'quarter' | 'year';

export interface ForecastResponse {
  pipeline: string;
  period: string;
  stages: ForecastStage[];
  totals: ForecastTotals;
}

// --- Import ---

export type ImportEntityType = 'PERSON' | 'COMPANY' | 'DEAL';
export type ImportDuplicateStrategy = 'SKIP' | 'UPDATE' | 'MARK';

export interface ImportPreviewResponse {
  importId: string;
  columns: string[];
  rows: Record<string, string>[];
  totalRows: number;
  format: string;
  availableTargetFields?: string[];
}

export interface ImportExecuteRequest {
  importId: string;
  entityType: ImportEntityType;
  mapping: Record<string, string>;
  duplicateStrategy: ImportDuplicateStrategy;
  options: {
    skipFirstRow?: boolean;
  };
}

export interface ImportErrorDetail {
  row: number;
  field: string;
  message: string;
}

export interface ImportExecuteResponse {
  created: number;
  updated: number;
  skipped: number;
  errors: number;
  errorDetails: ImportErrorDetail[];
}

// --- Enrichment ---

/** Einzelner Vorschlag (normalisiert für die UI) */
export interface EnrichmentSuggestion {
  field: string;
  current: string | null;
  suggested: string | null;
  source: string;
}

/** Backend-Antwort: suggestions als Record<field, {...}> */
export interface EnrichmentResponseRaw {
  companyId?: string;
  companyName?: string;
  sources?: string[];
  suggestions: Record<string, { current: string | null; suggested: string | null; source: string }>;
  enrichedAt: string;
  warnings?: string[];
}

/** Normalisierte Variante für die UI (backward-compat alias) */
export type EnrichmentResponse = EnrichmentResponseRaw;

export interface EnrichmentConfig {
  apiKey: string;
  configured: boolean;
}

// ============================================================
//  Microsoft 365 Integration (Phase 3)
// ============================================================

export interface UserIntegration {
  provider: string;
  connected: boolean;
  scopes: string[];
  expiresAt: string | null;
  msTenantId: string | null;
}

export interface M365EmailAddress {
  name?: string;
  address?: string;
}

export interface M365Email {
  id: string;
  subject: string | null;
  bodyPreview: string;
  receivedDateTime: string;
  from: { emailAddress: M365EmailAddress } | null;
  toRecipients: Array<{ emailAddress: M365EmailAddress }>;
  hasAttachments: boolean;
  isRead: boolean;
  webLink: string;
}

export interface M365CalendarEvent {
  id: string;
  subject: string;
  start: { dateTime: string; timeZone: string };
  end: { dateTime: string; timeZone: string };
  location?: { displayName?: string };
  organizer?: { emailAddress: M365EmailAddress };
  attendees?: Array<{ emailAddress: { name: string; address: string }; type: string }>;
  isOnlineMeeting: boolean;
  onlineMeetingUrl?: string;
  webLink: string;
}

export interface M365Task {
  id: string;
  title: string;
  status: 'notStarted' | 'inProgress' | 'completed' | 'waitingOnOthers' | 'deferred';
  importance: 'low' | 'normal' | 'high';
  dueDateTime?: { dateTime: string; timeZone: string } | null;
  completedDateTime?: { dateTime: string; timeZone: string } | null;
  createdDateTime: string;
}

export interface M365TaskList {
  id: string;
  displayName: string;
  tasks: M365Task[];
}

/** Flache Aufgabe inkl. Body-Inhalt (für Dashboard Aufgaben-Tab) */
export interface M365TaskFlat {
  id: string;
  listId: string;
  listName: string;
  title: string;
  status: string;
  importance: 'low' | 'normal' | 'high';
  dueDateTime?: { dateTime: string; timeZone: string } | null;
  bodyContent?: string | null; // Enthält "[INSIGHT_CRM:{activityId}]" wenn synchronisiert
  createdDateTime: string;
}

/** Offene CRM-Aufgabe (TASK / FOLLOWUP, noch nicht erledigt) */
export interface CrmOpenTask {
  id: string;
  type: 'TASK' | 'FOLLOWUP';
  subject: string;
  description: string | null;
  scheduledAt: string | null;
  contactId: string | null;
  companyId: string | null;
  contact?: {
    id: string;
    firstName: string | null;
    lastName: string | null;
    companyName: string | null;
  } | null;
  company?: { id: string; name: string } | null;
}

export interface M365Contact {
  id: string;
  displayName: string;
  emailAddresses: Array<{ name?: string; address?: string }>;
  mobilePhone: string | null;
  businessPhones: string[];
  jobTitle: string | null;
  companyName: string | null;
}

export interface M365MailFolder {
  id: string;
  displayName: string;
  totalItemCount: number;
  unreadItemCount: number;
  childFolderCount: number;
  wellKnownName?: string | null; // optional — nicht von allen Exchange-Tenants unterstützt
}

/** Microsoft-365-Benutzerprofil (für Profilanreicherung) */
export interface M365UserProfile {
  givenName: string | null;
  surname: string | null;
  displayName: string | null;
  mobilePhone: string | null;
  businessPhones: string[];
  city: string | null;
  streetAddress: string | null;
  postalCode: string | null;
  jobTitle: string | null;
  department: string | null;
  companyName: string | null;
  officeLocation: string | null;
}

/** Minimaler CRM-Kontakt für E-Mail-Lookup */
export interface CrmContactLookup {
  id: string;
  firstName: string | null;
  lastName: string | null;
  email: string | null;
  companyName: string | null;
}
