/**
 * Onboarding step 3 — email adapter credential persistence.
 */
import type { Db, DbTx } from '@zync/db'
import { saveAdapterCredential } from '@zync/notifications'

type DbOrTx = Db | DbTx

export type EmailAdapterKind = 'smtp' | 'skip'

export type SmtpCreds = {
  host: string
  port: number
  username: string
  password: string
}

export async function applyEmailAdapter(
  db: DbOrTx,
  tenantId: string,
  adapter: EmailAdapterKind,
  encryptionKey: string,
  creds?: SmtpCreds,
): Promise<void> {
  if (adapter === 'skip') return

  if (adapter === 'smtp') {
    if (!creds) {
      throw new Error('SMTP credentials required')
    }
    await saveAdapterCredential(
      db as Db,
      tenantId,
      'smtp',
      JSON.stringify({
        host: creds.host,
        port: creds.port,
        username: creds.username,
        password: creds.password,
      }),
      { source: 'onboarding' },
      encryptionKey,
    )
  }
}
