/**
 * HubSpot MCP Server - TypeScript Type Definitions
 * Based on HubSpot CRM API v3
 */

// Branded ID types (HubSpot uses numeric string IDs)
export type ContactId = string & { readonly __brand: 'ContactId' };
export type CompanyId = string & { readonly __brand: 'CompanyId' };
export type DealId = string & { readonly __brand: 'DealId' };
export type TicketId = string & { readonly __brand: 'TicketId' };
export type LineItemId = string & { readonly __brand: 'LineItemId' };
export type ProductId = string & { readonly __brand: 'ProductId' };
export type QuoteId = string & { readonly __brand: 'QuoteId' };
export type EngagementId = string & { readonly __brand: 'EngagementId' };
export type OwnerId = string & { readonly __brand: 'OwnerId' };
export type TeamId = string & { readonly __brand: 'TeamId' };
export type PipelineId = string & { readonly __brand: 'PipelineId' };
export type StageId = string & { readonly __brand: 'StageId' };
export type EmailId = string & { readonly __brand: 'EmailId' };
export type CampaignId = string & { readonly __brand: 'CampaignId' };
export type FormId = string & { readonly __brand: 'FormId' };
export type ListId = string & { readonly __brand: 'ListId' };
export type WorkflowId = string & { readonly __brand: 'WorkflowId' };
export type BlogId = string & { readonly __brand: 'BlogId' };
export type BlogPostId = string & { readonly __brand: 'BlogPostId' };
export type PageId = string & { readonly __brand: 'PageId' };
export type HubDbTableId = string & { readonly __brand: 'HubDbTableId' };
export type HubDbRowId = string & { readonly __brand: 'HubDbRowId' };
export type TimelineEventTypeId = string & { readonly __brand: 'TimelineEventTypeId' };
export type WebhookId = string & { readonly __brand: 'WebhookId' };

// Generic object ID
export type HubSpotObjectId = string;

// Standard HubSpot object format
export interface HubSpotObject<T extends Record<string, any> = Record<string, any>> {
  id: HubSpotObjectId;
  properties: T;
  createdAt: string;
  updatedAt: string;
  archived: boolean;
  archivedAt?: string;
}

// CRM Object Types
export type CRMObjectType =
  | 'contacts'
  | 'companies'
  | 'deals'
  | 'tickets'
  | 'line_items'
  | 'products'
  | 'quotes';

// Contact properties
export interface ContactProperties {
  email?: string;
  firstname?: string;
  lastname?: string;
  phone?: string;
  company?: string;
  website?: string;
  lifecyclestage?: string;
  hs_lead_status?: string;
  jobtitle?: string;
  address?: string;
  city?: string;
  state?: string;
  zip?: string;
  country?: string;
  [key: string]: any;
}

export interface Contact extends HubSpotObject<ContactProperties> {
  id: ContactId;
}

// Company properties
export interface CompanyProperties {
  name?: string;
  domain?: string;
  industry?: string;
  phone?: string;
  city?: string;
  state?: string;
  country?: string;
  website?: string;
  numberofemployees?: string;
  annualrevenue?: string;
  description?: string;
  type?: string;
  [key: string]: any;
}

export interface Company extends HubSpotObject<CompanyProperties> {
  id: CompanyId;
}

// Deal properties
export interface DealProperties {
  dealname?: string;
  amount?: string;
  closedate?: string;
  dealstage?: string;
  pipeline?: string;
  hubspot_owner_id?: string;
  description?: string;
  deal_currency_code?: string;
  [key: string]: any;
}

export interface Deal extends HubSpotObject<DealProperties> {
  id: DealId;
}

// Ticket properties
export interface TicketProperties {
  subject?: string;
  content?: string;
  hs_ticket_priority?: string;
  hs_pipeline_stage?: string;
  hs_pipeline?: string;
  hubspot_owner_id?: string;
  hs_ticket_category?: string;
  [key: string]: any;
}

export interface Ticket extends HubSpotObject<TicketProperties> {
  id: TicketId;
}

// Line Item properties
export interface LineItemProperties {
  name?: string;
  price?: string;
  quantity?: string;
  amount?: string;
  hs_sku?: string;
  description?: string;
  discount?: string;
  [key: string]: any;
}

export interface LineItem extends HubSpotObject<LineItemProperties> {
  id: LineItemId;
}

// Product properties
export interface ProductProperties {
  name?: string;
  description?: string;
  price?: string;
  hs_sku?: string;
  hs_cost_of_goods_sold?: string;
  hs_recurring_billing_period?: string;
  [key: string]: any;
}

export interface Product extends HubSpotObject<ProductProperties> {
  id: ProductId;
}

// Quote properties
export interface QuoteProperties {
  hs_title?: string;
  hs_expiration_date?: string;
  hs_status?: string;
  hs_public_url_key?: string;
  [key: string]: any;
}

export interface Quote extends HubSpotObject<QuoteProperties> {
  id: QuoteId;
}

// Associations
export interface AssociationType {
  associationCategory: 'HUBSPOT_DEFINED' | 'USER_DEFINED' | 'INTEGRATOR_DEFINED';
  associationTypeId: number;
}

export interface Association {
  id: HubSpotObjectId;
  type: string;
}

export interface AssociationResult {
  from: {
    id: HubSpotObjectId;
  };
  to: Array<{
    id: HubSpotObjectId;
    type: string;
  }>;
}

export interface BatchAssociation {
  from: {
    id: HubSpotObjectId;
  };
  to: {
    id: HubSpotObjectId;
  };
  type: AssociationType;
}

// Engagement types
export type EngagementType = 'NOTE' | 'CALL' | 'EMAIL' | 'MEETING' | 'TASK';

export interface EngagementProperties {
  hs_timestamp?: string;
  hs_engagement_type?: EngagementType;
  hs_body_preview?: string;
  hubspot_owner_id?: string;
  [key: string]: any;
}

export interface NoteProperties extends EngagementProperties {
  hs_note_body?: string;
}

export interface CallProperties extends EngagementProperties {
  hs_call_title?: string;
  hs_call_body?: string;
  hs_call_duration?: string;
  hs_call_status?: string;
  hs_call_direction?: string;
}

export interface EmailEngagementProperties extends EngagementProperties {
  hs_email_subject?: string;
  hs_email_text?: string;
  hs_email_html?: string;
  hs_email_status?: string;
}

export interface MeetingProperties extends EngagementProperties {
  hs_meeting_title?: string;
  hs_meeting_body?: string;
  hs_meeting_start_time?: string;
  hs_meeting_end_time?: string;
  hs_meeting_outcome?: string;
}

export interface TaskProperties extends EngagementProperties {
  hs_task_subject?: string;
  hs_task_body?: string;
  hs_task_status?: string;
  hs_task_priority?: string;
  hs_task_type?: string;
}

export interface Engagement extends HubSpotObject<EngagementProperties> {
  id: EngagementId;
}

// Pipeline & Stages
export interface PipelineStage {
  id: StageId;
  label: string;
  displayOrder: number;
  metadata: Record<string, any>;
  createdAt: string;
  updatedAt: string;
  archived: boolean;
}

export interface Pipeline {
  id: PipelineId;
  label: string;
  displayOrder: number;
  stages: PipelineStage[];
  createdAt: string;
  updatedAt: string;
  archived: boolean;
}

// Owner & Team
export interface Owner {
  id: OwnerId;
  email: string;
  firstName?: string;
  lastName?: string;
  userId?: number;
  createdAt: string;
  updatedAt: string;
  archived: boolean;
  teams?: Array<{ id: TeamId; name: string }>;
}

export interface Team {
  id: TeamId;
  name: string;
  userIds: number[];
  createdAt: string;
  updatedAt: string;
}

// Properties
export interface PropertyDefinition {
  name: string;
  label: string;
  type: 'string' | 'number' | 'date' | 'datetime' | 'enumeration' | 'bool';
  fieldType: string;
  description?: string;
  groupName?: string;
  options?: Array<{
    label: string;
    value: string;
    displayOrder: number;
    hidden: boolean;
  }>;
  createdAt?: string;
  updatedAt?: string;
  hidden: boolean;
  displayOrder?: number;
  calculated: boolean;
  externalOptions: boolean;
  hasUniqueValue: boolean;
  formField: boolean;
}

export interface PropertyGroup {
  name: string;
  label: string;
  displayOrder: number;
  properties: string[];
}

// Marketing - Email
export interface MarketingEmail {
  id: EmailId;
  name: string;
  subject: string;
  fromName?: string;
  replyTo?: string;
  created: string;
  updated: string;
  state?: string;
  campaignGuid?: string;
}

// Marketing - Campaign
export interface Campaign {
  id: CampaignId;
  name: string;
  created: string;
  updated: string;
  counters?: {
    sent?: number;
    delivered?: number;
    open?: number;
    click?: number;
  };
}

// Marketing - Form
export interface Form {
  guid: FormId;
  name: string;
  createdAt: string;
  updatedAt: string;
  archived: boolean;
  formType: string;
  submitText?: string;
  redirect?: string;
  formFieldGroups?: any[];
}

// Marketing - List
export interface List {
  listId: ListId;
  name: string;
  dynamic: boolean;
  createdAt: string;
  updatedAt: string;
  filters?: any[];
  metaData?: {
    size?: number;
    processing?: string;
  };
}

// Marketing - Workflow
export interface Workflow {
  id: WorkflowId;
  name: string;
  type: string;
  enabled: boolean;
  createdAt: number;
  updatedAt: number;
  contactListIds?: {
    enrolled?: number[];
    active?: number[];
    completed?: number[];
  };
}

// CMS - Blog
export interface Blog {
  id: BlogId;
  name: string;
  created: string;
  updated: string;
  domain?: string;
  language?: string;
}

export interface BlogPost {
  id: BlogPostId;
  name: string;
  slug: string;
  contentGroupId: BlogId;
  created: string;
  updated: string;
  published: string;
  authorName?: string;
  state: string;
  htmlTitle?: string;
  metaDescription?: string;
  postBody?: string;
  postSummary?: string;
}

// CMS - Page
export interface Page {
  id: PageId;
  name: string;
  slug: string;
  created: string;
  updated: string;
  published?: string;
  domain?: string;
  htmlTitle?: string;
  metaDescription?: string;
}

// CMS - HubDB
export interface HubDbTable {
  id: HubDbTableId;
  name: string;
  label: string;
  columns: Array<{
    id: string;
    name: string;
    label: string;
    type: string;
  }>;
  rowCount: number;
  createdAt: string;
  updatedAt: string;
  published: boolean;
}

export interface HubDbRow {
  id: HubDbRowId;
  path?: string;
  name?: string;
  values: Record<string, any>;
  createdAt: string;
  updatedAt: string;
}

// Search API
export interface FilterGroup {
  filters: Filter[];
}

export interface Filter {
  propertyName: string;
  operator: FilterOperator;
  value?: string | number | boolean;
  values?: string[];
}

export type FilterOperator =
  | 'EQ'
  | 'NEQ'
  | 'LT'
  | 'LTE'
  | 'GT'
  | 'GTE'
  | 'BETWEEN'
  | 'IN'
  | 'NOT_IN'
  | 'HAS_PROPERTY'
  | 'NOT_HAS_PROPERTY'
  | 'CONTAINS_TOKEN'
  | 'NOT_CONTAINS_TOKEN';

export interface Sort {
  propertyName: string;
  direction: 'ASCENDING' | 'DESCENDING';
}

export interface SearchRequest {
  filterGroups?: FilterGroup[];
  sorts?: Sort[];
  query?: string;
  properties?: string[];
  limit?: number;
  after?: string;
}

export interface SearchResponse<T> {
  total: number;
  results: T[];
  paging?: {
    next?: {
      after: string;
      link?: string;
    };
  };
}

// Webhooks
export interface Webhook {
  id: WebhookId;
  createdAt: string;
  updatedAt: string;
  active: boolean;
  eventType: string;
  targetUrl: string;
}

// Timeline Events
export interface TimelineEventType {
  id: TimelineEventTypeId;
  name: string;
  headerTemplate?: string;
  detailTemplate?: string;
  objectType: string;
  applicationId: string;
  createdAt: string;
  updatedAt: string;
}

export interface TimelineEvent {
  id: string;
  eventTemplateId: TimelineEventTypeId;
  objectId: HubSpotObjectId;
  timestamp: string;
  tokens?: Record<string, string>;
  extraData?: Record<string, any>;
}

// Pagination
export interface PaginationInfo {
  next?: {
    after: string;
    link?: string;
  };
  prev?: {
    before: string;
    link?: string;
  };
}

export interface PagedResponse<T> {
  results: T[];
  paging?: PaginationInfo;
}

// Batch operations
export interface BatchReadRequest {
  properties?: string[];
  propertiesWithHistory?: string[];
  idProperty?: string;
  inputs: Array<{ id: string }>;
}

export interface BatchCreateRequest<T> {
  inputs: Array<{ properties: T }>;
}

export interface BatchUpdateRequest<T> {
  inputs: Array<{ id: string; properties: T }>;
}

export interface BatchArchiveRequest {
  inputs: Array<{ id: string }>;
}

export interface BatchResponse<T> {
  status: 'PENDING' | 'PROCESSING' | 'CANCELED' | 'COMPLETE';
  results: T[];
  numErrors?: number;
  errors?: Array<{
    status: string;
    category: string;
    message: string;
    context?: Record<string, any>;
  }>;
  startedAt: string;
  completedAt: string;
}

// API Error Response
export interface HubSpotError {
  status: string;
  message: string;
  correlationId: string;
  category: string;
  errors?: Array<{
    message: string;
    in?: string;
  }>;
}
