import type { AutomationDomain } from './domains'
import { DOMAIN_TRIGGER_TYPES, TRIGGER_LABELS } from './domains'
import type { TriggerType } from './types'
import {
  defaultDriveScope,
  defaultMailScope,
  type ApiTokenDriveScope,
  type ApiTokenMailScope,
} from './api-token-permissions'

export interface WebhookContactsScope {
  all_books: boolean
  book_ids: string[]
}

export interface WebhookAgendaScope {
  all_calendars: boolean
  calendar_ids: string[]
}

export function defaultContactsScope(): WebhookContactsScope {
  return { all_books: true, book_ids: [] }
}

export function defaultAgendaScope(): WebhookAgendaScope {
  return { all_calendars: true, calendar_ids: [] }
}

export type WebhookEventOption = {
  value: TriggerType
  label: string
  domain: AutomationDomain
}

export const WEBHOOK_EVENT_OPTIONS: WebhookEventOption[] = (
  ['mail', 'drive', 'contacts', 'agenda'] as AutomationDomain[]
).flatMap((domain) =>
  DOMAIN_TRIGGER_TYPES[domain].map((value) => ({
    value,
    label: TRIGGER_LABELS[value],
    domain,
  }))
)

export function defaultEventTypesForDomain(domain: AutomationDomain): TriggerType[] {
  return [...DOMAIN_TRIGGER_TYPES[domain]]
}

export function eventDomainsFromTypes(types: TriggerType[]): AutomationDomain[] {
  const domains = new Set<AutomationDomain>()
  for (const type of types) {
    const opt = WEBHOOK_EVENT_OPTIONS.find((o) => o.value === type)
    if (opt) domains.add(opt.domain)
  }
  return [...domains]
}

export function hasMailWebhookEvents(types: TriggerType[]): boolean {
  return types.some((t) => DOMAIN_TRIGGER_TYPES.mail.includes(t))
}

export function hasDriveWebhookEvents(types: TriggerType[]): boolean {
  return types.some((t) => DOMAIN_TRIGGER_TYPES.drive.includes(t))
}

export function hasContactsWebhookEvents(types: TriggerType[]): boolean {
  return types.some((t) => DOMAIN_TRIGGER_TYPES.contacts.includes(t))
}

export function hasAgendaWebhookEvents(types: TriggerType[]): boolean {
  return types.some((t) => DOMAIN_TRIGGER_TYPES.agenda.includes(t))
}

export type WebhookFormState = {
  name: string
  url: string
  template: string
  eventTypes: TriggerType[]
  mailScope: ApiTokenMailScope
  driveScope: ApiTokenDriveScope
  contactsScope: WebhookContactsScope
  agendaScope: WebhookAgendaScope
}

export function createDefaultWebhookForm(domain: AutomationDomain = 'mail'): WebhookFormState {
  return {
    name: '',
    url: '',
    template: '',
    eventTypes: defaultEventTypesForDomain(domain),
    mailScope: defaultMailScope(),
    driveScope: defaultDriveScope(),
    contactsScope: defaultContactsScope(),
    agendaScope: defaultAgendaScope(),
  }
}
