import type { ApiMailSettings } from '@/lib/api/types'
import type {
  InboxSortMode,
  MailBackgroundId,
  MailDensity,
  MailThemeMode,
  ReadingPaneMode,
} from '@/lib/mail-settings/types'

export type NotificationPrefs = {
  desktopNewMail: boolean
  desktopMentions: boolean
  emailDigest: boolean
  soundEnabled: boolean
}

export const defaultNotificationPrefs: NotificationPrefs = {
  desktopNewMail: true,
  desktopMentions: true,
  emailDigest: false,
  soundEnabled: false,
}

export function apiSettingsToStore(settings: ApiMailSettings) {
  const n = settings.notifications
  return {
    density: settings.density as MailDensity,
    themeMode: settings.theme_mode as MailThemeMode,
    backgroundId: settings.background_id as MailBackgroundId,
    inboxSort: settings.inbox_sort as InboxSortMode,
    readingPane: settings.reading_pane as ReadingPaneMode,
    conversationMode: settings.conversation_mode,
    desktopNewMail: n?.desktop_new_mail ?? defaultNotificationPrefs.desktopNewMail,
    desktopMentions: n?.desktop_mentions ?? defaultNotificationPrefs.desktopMentions,
    emailDigest: n?.email_digest ?? defaultNotificationPrefs.emailDigest,
    soundEnabled: n?.sound_enabled ?? defaultNotificationPrefs.soundEnabled,
  }
}

export function storeSettingsToPatch(settings: {
  density?: MailDensity
  themeMode?: MailThemeMode
  backgroundId?: MailBackgroundId
  inboxSort?: InboxSortMode
  readingPane?: ReadingPaneMode
  conversationMode?: boolean
  desktopNewMail?: boolean
  desktopMentions?: boolean
  emailDigest?: boolean
  soundEnabled?: boolean
}): Partial<ApiMailSettings> {
  const patch: Partial<ApiMailSettings> = {}
  if (settings.density !== undefined) patch.density = settings.density
  if (settings.themeMode !== undefined) patch.theme_mode = settings.themeMode
  if (settings.backgroundId !== undefined) patch.background_id = settings.backgroundId
  if (settings.inboxSort !== undefined) patch.inbox_sort = settings.inboxSort
  if (settings.readingPane !== undefined) patch.reading_pane = settings.readingPane
  if (settings.conversationMode !== undefined) {
    patch.conversation_mode = settings.conversationMode
  }

  const notificationPatch: Partial<NonNullable<ApiMailSettings['notifications']>> = {}
  if (settings.desktopNewMail !== undefined) {
    notificationPatch.desktop_new_mail = settings.desktopNewMail
  }
  if (settings.desktopMentions !== undefined) {
    notificationPatch.desktop_mentions = settings.desktopMentions
  }
  if (settings.emailDigest !== undefined) notificationPatch.email_digest = settings.emailDigest
  if (settings.soundEnabled !== undefined) notificationPatch.sound_enabled = settings.soundEnabled
  if (Object.keys(notificationPatch).length > 0) {
    patch.notifications = notificationPatch as ApiMailSettings['notifications']
  }

  return patch
}
