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 function defaultContactsScope(): WebhookContactsScope { return { all_books: true, book_ids: [] } } export type WebhookEventOption = { value: TriggerType label: string domain: AutomationDomain } export const WEBHOOK_EVENT_OPTIONS: WebhookEventOption[] = ( ['mail', 'drive', 'contacts'] 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() 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 type WebhookFormState = { name: string url: string template: string eventTypes: TriggerType[] mailScope: ApiTokenMailScope driveScope: ApiTokenDriveScope contactsScope: WebhookContactsScope } export function createDefaultWebhookForm(domain: AutomationDomain = 'mail'): WebhookFormState { return { name: '', url: '', template: '', eventTypes: defaultEventTypesForDomain(domain), mailScope: defaultMailScope(), driveScope: defaultDriveScope(), contactsScope: defaultContactsScope(), } }