/**
 * Email Account plugins for Vue3 frontend
 * Ported from jingrow/email/pagetype/email_account/email_account.js
 *
 * Key behaviors:
 * - domain change → fetch domain values (smtp_server, use_ssl, etc.)
 * - service change → apply email defaults (GMail, Outlook, etc.)
 * - new record → add default INBOX to imap_folder
 */
import type { FieldWatchPlugin, RecordInitPlugin } from '@/core/plugins/fieldPlugin'
import { api } from '@/shared/api/common'

// Fields fetched from Email Domain (mirrors EMAIL_DOMAIN_FIELDS in backend)
const DOMAIN_FIELDS = [
  'email_server',
  'use_imap',
  'use_ssl',
  'use_starttls',
  'use_tls',
  'attachment_limit',
  'smtp_server',
  'smtp_port',
  'use_ssl_for_outgoing',
  'append_emails_to_sent_folder',
  'incoming_port',
]

// ============================================
// Email service defaults (from old email_account.js)
// ============================================
const emailDefaults: Record<string, Record<string, any>> = {
  GMail: {
    email_server: 'imap.gmail.com',
    incoming_port: 993,
    use_ssl: 1,
    enable_outgoing: 1,
    smtp_server: 'smtp.gmail.com',
    smtp_port: 587,
    use_tls: 1,
    use_imap: 1,
  },
  'Outlook.com': {
    email_server: 'imap-mail.outlook.com',
    use_ssl: 1,
    enable_outgoing: 1,
    smtp_server: 'smtp-mail.outlook.com',
    smtp_port: 587,
    use_tls: 1,
    use_imap: 1,
  },
  Sendgrid: {
    enable_outgoing: 1,
    smtp_server: 'smtp.sendgrid.net',
    smtp_port: 587,
    use_tls: 1,
  },
  SparkPost: {
    enable_incoming: 0,
    enable_outgoing: 1,
    smtp_server: 'smtp.sparkpostmail.com',
    smtp_port: 587,
    use_tls: 1,
  },
  'Yahoo Mail': {
    email_server: 'imap.mail.yahoo.com',
    use_ssl: 1,
    enable_outgoing: 1,
    smtp_server: 'smtp.mail.yahoo.com',
    smtp_port: 587,
    use_tls: 1,
    use_imap: 1,
  },
  'Yandex.Mail': {
    email_server: 'imap.yandex.com',
    use_ssl: 1,
    enable_outgoing: 1,
    smtp_server: 'smtp.yandex.com',
    smtp_port: 587,
    use_tls: 1,
    use_imap: 1,
  },
}

const emailDefaultsPop: Record<string, Record<string, any>> = {
  GMail: { email_server: 'pop.gmail.com' },
  'Outlook.com': { email_server: 'pop3-mail.outlook.com' },
  'Yahoo Mail': { email_server: 'pop.mail.yahoo.com' },
  'Yandex.Mail': { email_server: 'pop.yandex.com' },
}

// ============================================
// Domain plugin - fetch domain values when domain changes
// ============================================

const domainPlugin: FieldWatchPlugin = {
  fieldname: 'domain',
  handler: async (ctx) => {
    const domain = ctx.value
    if (!domain) return

    try {
      // Use jingrow.client.get_value to fetch domain settings directly
      // (get_domain_values is an instance method and can't be called as standalone RPC)
      const res = await api.call('jingrow.client.get_value', {
        pagetype: 'Email Domain',
        fieldname: JSON.stringify(DOMAIN_FIELDS),
        filters: JSON.stringify({ name: domain }),
        as_dict: 1,
      })
      const domainValues = res?.message ?? res
      if (domainValues && typeof domainValues === 'object') {
        for (const [field, value] of Object.entries(domainValues)) {
          if (value !== null && value !== undefined) {
            ctx.record[field] = value
          }
        }
      }
    } catch (err) {
      console.error('[EmailAccount] Failed to fetch domain values:', err)
    }
  },
}

// ============================================
// Service plugin - apply defaults when service changes
// ============================================
const servicePlugin: FieldWatchPlugin = {
  fieldname: 'service',
  handler: (ctx) => {
    const service = ctx.value
    if (!service || !emailDefaults[service]) return

    const defaults = emailDefaults[service]
    for (const [key, value] of Object.entries(defaults)) {
      ctx.record[key] = value
    }

    // Apply POP3 defaults if not using IMAP
    if (!ctx.record.use_imap && emailDefaultsPop[service]) {
      const popDefaults = emailDefaultsPop[service]
      for (const [key, value] of Object.entries(popDefaults)) {
        ctx.record[key] = value
      }
    }
  },
}

// ============================================
// use_imap plugin - switch between IMAP/POP3 defaults
// ============================================
const useImapPlugin: FieldWatchPlugin = {
  fieldname: 'use_imap',
  handler: (ctx) => {
    const service = ctx.record.service
    if (!service) return

    if (!ctx.value) {
      // Not using IMAP → apply POP3 defaults
      if (emailDefaultsPop[service]) {
        for (const [key, value] of Object.entries(emailDefaultsPop[service])) {
          ctx.record[key] = value
        }
      }
    } else {
      // Using IMAP → apply IMAP defaults
      if (emailDefaults[service]) {
        for (const [key, value] of Object.entries(emailDefaults[service])) {
          ctx.record[key] = value
        }
      }
    }
  },
}

// ============================================
// Record init plugin - add default INBOX for new records
// ============================================
const recordInitPlugin: RecordInitPlugin = {
  pagetype: 'Email Account',
  handler: (record) => {
    // Add default IMAP INBOX folder for new records
    if (!record.imap_folder || !Array.isArray(record.imap_folder) || record.imap_folder.length === 0) {
      record.imap_folder = [{ folder_name: 'INBOX' }]
    }
  },
}

// Export as default array - pluginLoader will auto-register them
export default [domainPlugin, servicePlugin, useImapPlugin, recordInitPlugin]
