import apiClient from './client'

export type ConditionField = 'from_address' | 'to_address' | 'subject' | 'mailbox_id' | 'pec_type'
export type ConditionOperator = 'contains' | 'equals' | 'starts_with' | 'ends_with' | 'regex' | 'not_contains'
export type ActionType = 'apply_label' | 'assign_vbox' | 'mark_read' | 'mark_starred' | 'notify_webhook'

export interface RoutingRuleCondition {
  id: string
  field: ConditionField
  operator: ConditionOperator
  value: string
}

export interface RoutingRuleAction {
  id: string
  action_type: ActionType
  action_value: string | null
}

export interface RoutingRuleResponse {
  id: string
  tenant_id: string
  name: string
  description: string | null
  is_active: boolean
  priority: number
  stop_processing: boolean
  conditions: RoutingRuleCondition[]
  actions: RoutingRuleAction[]
  created_by: string | null
  created_at: string
  updated_at: string
}

export interface RoutingRuleCreate {
  name: string
  description?: string | null
  is_active?: boolean
  priority?: number
  stop_processing?: boolean
  conditions?: Array<{ field: ConditionField; operator: ConditionOperator; value: string }>
  actions?: Array<{ action_type: ActionType; action_value?: string | null }>
}

export type RoutingRuleUpdate = Partial<RoutingRuleCreate>

export const routingRulesApi = {
  list: () =>
    apiClient.get<{ items: RoutingRuleResponse[]; total: number }>('/routing-rules').then((r) => r.data),

  get: (id: string) =>
    apiClient.get<RoutingRuleResponse>(`/routing-rules/${id}`).then((r) => r.data),

  create: (data: RoutingRuleCreate) =>
    apiClient.post<RoutingRuleResponse>('/routing-rules', data).then((r) => r.data),

  update: (id: string, data: RoutingRuleUpdate) =>
    apiClient.put<RoutingRuleResponse>(`/routing-rules/${id}`, data).then((r) => r.data),

  delete: (id: string) =>
    apiClient.delete(`/routing-rules/${id}`).then((r) => r.data),

  toggle: (id: string) =>
    apiClient.post<RoutingRuleResponse>(`/routing-rules/${id}/toggle`).then((r) => r.data),
}
