// Server-only email: Gmail SMTP client, purchase receipts and the email log.
// Credentials come from /admin/settings, falling back to environment
// variables, like the Moolre and voice settings.
import { desc, eq, like } from 'drizzle-orm'
import nodemailer from 'nodemailer'
import { db } from '../../db/index.js'
import { accounts, appSettings, emailMessages, payments } from '../../db/schema.js'
import { EMAIL_DEFAULTS, EMAIL_FIELDS, type EmailFieldKey } from './email'
import { formatCedis, getPackage } from './pricing'

const SETTING_PREFIX = 'email.'
const RECEIPTS_KEY = 'receipts.enabled'
const CACHE_MS = 30_000

export type EmailConfig = Record<EmailFieldKey, string> & { receiptsEnabled: boolean }

let cached: { at: number; values: Map<string, string> } | null = null

async function savedRows() {
  return db.select().from(appSettings).where(like(appSettings.key, `${SETTING_PREFIX}%`))
}

export async function getEmailConfig(): Promise<EmailConfig> {
  if (!cached || Date.now() - cached.at >= CACHE_MS) {
    const rows = await savedRows()
    cached = { at: Date.now(), values: new Map(rows.map((r) => [r.key.slice(SETTING_PREFIX.length), r.value])) }
  }
  const config = { receiptsEnabled: cached.values.get(RECEIPTS_KEY) !== 'false' } as EmailConfig
  for (const field of EMAIL_FIELDS) {
    config[field.key] = (cached.values.get(field.key) || process.env[field.env] || EMAIL_DEFAULTS[field.key]).trim()
  }
  // Gmail shows app passwords in groups of four; the spaces aren't part of it.
  config.appPassword = config.appPassword.replace(/\s+/g, '')
  return config
}

// Where each value currently comes from, for the settings page. Always reads fresh.
export async function getEmailConfigSources() {
  const rows = await savedRows()
  const saved = new Map(rows.map((r) => [r.key.slice(SETTING_PREFIX.length), r]))
  return {
    saved,
    receiptsEnabled: saved.get(RECEIPTS_KEY)?.value !== 'false',
    envSet: Object.fromEntries(EMAIL_FIELDS.map((f) => [f.key, Boolean(process.env[f.env])])) as Record<EmailFieldKey, boolean>,
  }
}

export async function saveEmailSettings(changes: Record<string, string | null>, updatedBy: string) {
  for (const [key, value] of Object.entries(changes)) {
    const dbKey = `${SETTING_PREFIX}${key}`
    if (value === null) {
      await db.delete(appSettings).where(eq(appSettings.key, dbKey))
    } else {
      await db
        .insert(appSettings)
        .values({ key: dbKey, value, updatedBy })
        .onConflictDoUpdate({ target: appSettings.key, set: { value, updatedBy, updatedAt: new Date() } })
    }
  }
  cached = null
}

export async function setReceiptsEnabled(enabled: boolean, updatedBy: string) {
  await saveEmailSettings({ [RECEIPTS_KEY]: String(enabled) }, updatedBy)
}

function transport(config: EmailConfig) {
  return nodemailer.createTransport({
    host: 'smtp.gmail.com',
    port: 465,
    secure: true,
    auth: { user: config.address, pass: config.appPassword },
    connectionTimeout: 10_000,
    greetingTimeout: 10_000,
    socketTimeout: 15_000,
  })
}

// Turns Gmail's SMTP errors into something an admin can act on.
function explain(error: unknown) {
  const message = error instanceof Error ? error.message : String(error)
  if (/535|534|Username and Password not accepted|Application-specific password required/i.test(message)) {
    return 'Gmail rejected the address and app password. Create a new app password for this Gmail account and save it again.'
  }
  if (/timeout|ETIMEDOUT|ECONNREFUSED|ENOTFOUND/i.test(message)) return 'Could not reach Gmail. Try again in a minute.'
  return message
}

// Logs in to Gmail with the given settings without sending anything.
export async function probeEmail(config: EmailConfig) {
  if (!config.address || !config.appPassword) return { ok: false as const, error: 'Add the Gmail address and app password first.' }
  const transporter = transport(config)
  try {
    await transporter.verify()
    return { ok: true as const, error: null }
  } catch (error) {
    return { ok: false as const, error: explain(error) }
  } finally {
    transporter.close()
  }
}

type Mail = { to: string; subject: string; text: string; html: string }

// Sends one email and logs it. Returns the outcome; never throws.
export async function deliverEmail(
  userId: string,
  kind: 'receipt' | 'test',
  mail: Mail,
  reference: string | null = null,
  config?: EmailConfig,
) {
  let error: string | null = null
  try {
    const settings = config ?? (await getEmailConfig())
    if (!settings.appPassword) error = 'No Gmail app password is set in the email settings.'
    else {
      const transporter = transport(settings)
      try {
        await transporter.sendMail({
          from: { name: settings.fromName, address: settings.address },
          replyTo: settings.address,
          ...mail,
        })
      } finally {
        transporter.close()
      }
    }
  } catch (err) {
    error = explain(err)
  }
  try {
    await db
      .insert(emailMessages)
      .values({ userId, kind, toEmail: mail.to, subject: mail.subject, reference, status: error ? 'failed' : 'sent', error })
  } catch (err) {
    console.error('Could not log email', err)
  }
  return { ok: !error, error }
}

export type ReceiptDetails = {
  name: string
  reference: string
  date: Date
  bundle: string
  credits: number
  amount: number
  balance: number
  payerPhone: string | null
  transactionId: string | null
}

const escapeHtml = (value: string) =>
  value.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]!)

function siteUrl() {
  return (process.env.URL || 'https://akotocreativesms.com').replace(/\/$/, '')
}

export function buildReceipt(details: ReceiptDetails, to: string): Mail {
  const date = new Intl.DateTimeFormat('en-GB', { timeZone: 'Africa/Accra', dateStyle: 'long', timeStyle: 'short' }).format(details.date)
  const rows: [string, string][] = [
    ['Receipt number', details.reference],
    ['Date', `${date} (Ghana time)`],
    ['Bundle', details.bundle],
    ['SMS credits', details.credits.toLocaleString('en-GH')],
    ['Paid with', `Mobile money${details.payerPhone ? ` (${details.payerPhone})` : ''}`],
    ...(details.transactionId ? ([['Transaction ID', details.transactionId]] as [string, string][]) : []),
    ['New credit balance', `${details.balance.toLocaleString('en-GH')} credits`],
  ]
  const total = formatCedis(details.amount)
  const dashboard = `${siteUrl()}/dashboard`
  const subject = `Your AkotoCreative SMS receipt · ${details.reference}`

  const text = [
    `Hi ${details.name},`,
    '',
    `Thank you for your purchase. ${details.credits.toLocaleString('en-GH')} SMS credits have been added to your AkotoCreative SMS account.`,
    '',
    ...rows.map(([label, value]) => `${label}: ${value}`),
    `Total paid: ${total}`,
    '',
    `View your balance and send messages: ${dashboard}`,
    '',
    'Questions about this payment? Reply to this email or use Chat with us on the website.',
    '',
    'AkotoCreative SMS',
  ].join('\n')

  const rowHtml = rows
    .map(
      ([label, value]) =>
        `<tr><td style="padding:10px 0;color:#6b6457;border-bottom:1px solid #ece6da">${escapeHtml(label)}</td><td style="padding:10px 0;text-align:right;font-weight:600;border-bottom:1px solid #ece6da">${escapeHtml(value)}</td></tr>`,
    )
    .join('')

  const html = `<!doctype html>
<html lang="en">
<body style="margin:0;background:#f6f2ea;font-family:Helvetica,Arial,sans-serif;color:#1f2a24">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f6f2ea;padding:32px 12px">
    <tr><td align="center">
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:560px;background:#ffffff;border-radius:18px;overflow:hidden;border:1px solid #e6dfd1">
        <tr><td style="height:6px;background:linear-gradient(90deg,#1e5b3a,#d9a21b,#b8432f,#1e5b3a)"></td></tr>
        <tr><td style="padding:28px 32px 8px">
          <p style="margin:0;font-size:13px;letter-spacing:2px;text-transform:uppercase;color:#1e5b3a;font-weight:700">AkotoCreative SMS</p>
          <h1 style="margin:10px 0 0;font-size:24px">Payment receipt</h1>
          <p style="margin:12px 0 0;font-size:15px;line-height:1.5">Hi ${escapeHtml(details.name)}, thank you for your purchase. <strong>${details.credits.toLocaleString('en-GH')} SMS credits</strong> have been added to your account.</p>
        </td></tr>
        <tr><td style="padding:16px 32px 0">
          <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="font-size:14px">
            ${rowHtml}
            <tr><td style="padding:14px 0;font-size:16px;font-weight:700">Total paid</td><td style="padding:14px 0;text-align:right;font-size:18px;font-weight:700;color:#1e5b3a">${escapeHtml(total)}</td></tr>
          </table>
        </td></tr>
        <tr><td style="padding:16px 32px 28px">
          <a href="${dashboard}" style="display:inline-block;background:#1e5b3a;color:#ffffff;text-decoration:none;font-weight:600;padding:12px 20px;border-radius:999px;font-size:14px">Go to your dashboard</a>
          <p style="margin:20px 0 0;font-size:13px;line-height:1.5;color:#6b6457">Questions about this payment? Reply to this email or use Chat with us on the website. Keep this email as your proof of payment.</p>
        </td></tr>
      </table>
      <p style="margin:16px 0 0;font-size:12px;color:#8a8273">AkotoCreative SMS · Bulk SMS for Ghana · <a href="${siteUrl()}" style="color:#8a8273">${escapeHtml(siteUrl().replace(/^https?:\/\//, ''))}</a></p>
    </td></tr>
  </table>
</body>
</html>`

  return { to, subject, text, html }
}

export const SAMPLE_RECEIPT: ReceiptDetails = {
  name: 'Ama',
  reference: 'AKC-SAMPLE',
  date: new Date(),
  bundle: 'Business',
  credits: 2_000,
  amount: 60,
  balance: 2_450,
  payerPhone: '233241234567',
  transactionId: null,
}

// Emails the receipt for a payment that was just claimed as successful, if
// receipts are on. Called once per payment by settlePayment; never throws.
export async function sendReceiptEmail(paymentId: number) {
  try {
    const config = await getEmailConfig()
    if (!config.receiptsEnabled || !config.appPassword) return
    const [row] = await db
      .select({ payment: payments, email: accounts.email, name: accounts.name, balance: accounts.credits })
      .from(payments)
      .innerJoin(accounts, eq(accounts.userId, payments.userId))
      .where(eq(payments.id, paymentId))
    if (!row || !row.email) return
    const { payment } = row
    const mail = buildReceipt(
      {
        name: row.name?.trim().split(/\s+/)[0] || 'there',
        reference: payment.reference,
        date: payment.completedAt ?? new Date(),
        bundle: getPackage(payment.packageId)?.name ?? 'SMS credit',
        credits: payment.credits,
        amount: Number(payment.amount),
        balance: row.balance,
        payerPhone: payment.payerPhone,
        transactionId: payment.providerReference,
      },
      row.email,
    )
    await deliverEmail(payment.userId, 'receipt', mail, payment.reference, config)
  } catch (error) {
    console.error('Receipt email failed', paymentId, error)
  }
}

export async function recentEmails(limit = 20) {
  return db
    .select({
      id: emailMessages.id,
      kind: emailMessages.kind,
      toEmail: emailMessages.toEmail,
      subject: emailMessages.subject,
      reference: emailMessages.reference,
      status: emailMessages.status,
      error: emailMessages.error,
      createdAt: emailMessages.createdAt,
    })
    .from(emailMessages)
    .orderBy(desc(emailMessages.createdAt))
    .limit(limit)
}
