import { createServerFn } from '@tanstack/react-start'
import { getRequestUrl } from '@tanstack/react-start/server'
import { and, asc, desc, eq, gte, ilike, isNull, sql, type AnyColumn } from 'drizzle-orm'
import { z } from 'zod'
import { db } from '../../db/index.js'
import { accounts, campaigns, chatMessages, creditAdjustments, payments, senderIds, voiceCalls } from '../../db/schema.js'
import { requireAdmin } from './identity.functions'
import { ensureAccount, settlePayment } from './billing.server'
import { deliverAutoSms, getAutoSmsSettings, recentAutoMessages, saveAutoSmsSetting } from './auto-sms.server'
import { AUTO_SMS_EVENTS, AUTO_SMS_MAX_LENGTH, renderAutoSms, sampleValues, type AutoSmsEvent } from './auto-sms'
import { notify } from './notifications.server'
import {
  createPaymentLink,
  getMoolreConfig,
  getMoolreConfigSources,
  getSmsBalance,
  MoolreError,
  probePaymentLogin,
  probeSms,
  saveMoolreSettings,
  type MoolreConfig,
} from './moolre.server'
import { MOOLRE_FIELDS, decodeMoolreKey, type MoolreEnvironment, type MoolreFieldKey } from './moolre-settings'
import { SENDER_ID_PATTERN, normalizeGhanaPhone, normalizeSenderId } from './sms'
import { getVoiceConfig, getVoiceConfigSources, probeVoice, saveVoiceSettings, voiceCallCounts, type VoiceConfig } from './voice.server'
import { VOICE_FIELDS, type VoiceFieldKey } from './voice'
import {
  SAMPLE_RECEIPT,
  buildReceipt,
  deliverEmail,
  getEmailConfig,
  getEmailConfigSources,
  probeEmail,
  recentEmails,
  saveEmailSettings,
  setReceiptsEnabled,
  type EmailConfig,
} from './email.server'
import { EMAIL_FIELDS, type EmailFieldKey } from './email'
import { getDeliveryLabels, recentDeliveryCodes, saveDeliveryLabels } from './delivery.server'
import { DELIVERY_CODES } from './delivery'

const STATUSES = ['pending', 'approved', 'rejected'] as const

export const getSenderIdRequests = createServerFn({ method: 'GET' })
  .middleware([requireAdmin])
  .validator(z.object({ status: z.enum(STATUSES) }))
  .handler(async ({ data }) => {
    const [rows, counts] = await Promise.all([
      db
        .select({
          id: senderIds.id,
          senderId: senderIds.senderId,
          purpose: senderIds.purpose,
          status: senderIds.status,
          reviewNote: senderIds.reviewNote,
          reviewedBy: senderIds.reviewedBy,
          createdAt: senderIds.createdAt,
          reviewedAt: senderIds.reviewedAt,
          email: accounts.email,
        })
        .from(senderIds)
        .innerJoin(accounts, eq(accounts.userId, senderIds.userId))
        .where(eq(senderIds.status, data.status))
        // Oldest first in the queue, most recently reviewed first otherwise.
        .orderBy(data.status === 'pending' ? asc(senderIds.createdAt) : desc(senderIds.reviewedAt))
        .limit(200),
      db
        .select({ status: senderIds.status, count: sql<number>`count(*)::int` })
        .from(senderIds)
        .groupBy(senderIds.status),
    ])
    const totals = { pending: 0, approved: 0, rejected: 0 }
    for (const c of counts) if (c.status in totals) totals[c.status as keyof typeof totals] = c.count
    return {
      totals,
      requests: rows.map((r) => ({
        ...r,
        createdAt: r.createdAt.toISOString(),
        reviewedAt: r.reviewedAt?.toISOString() ?? null,
      })),
    }
  })

export const reviewSenderId = createServerFn({ method: 'POST' })
  .middleware([requireAdmin])
  .validator(
    z.object({
      id: z.number().int().positive(),
      decision: z.enum(['approved', 'rejected', 'pending']),
      note: z.string().trim().max(300).optional(),
    }),
  )
  .handler(async ({ data, context }) => {
    const reviewed = data.decision !== 'pending'
    const [row] = await db
      .update(senderIds)
      .set({
        status: data.decision,
        reviewNote: data.note || null,
        reviewedBy: reviewed ? (context.user.email ?? context.user.id) : null,
        reviewedAt: reviewed ? new Date() : null,
      })
      .where(eq(senderIds.id, data.id))
      .returning({ id: senderIds.id, senderId: senderIds.senderId, status: senderIds.status })
    if (!row) throw new Error('That request no longer exists.')
    return row
  })

const iso = (d: Date | null) => d?.toISOString() ?? null

const DAY_MS = 24 * 60 * 60 * 1000
const TREND_DAYS = 30

// Builds the list of UTC days (YYYY-MM-DD) shown on the overview charts, oldest first.
function trendDays(now: Date) {
  const today = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
  return Array.from({ length: TREND_DAYS }, (_, i) =>
    new Date(today - (TREND_DAYS - 1 - i) * DAY_MS).toISOString().slice(0, 10),
  )
}

const dayOf = (column: AnyColumn) => sql<string>`to_char(date_trunc('day', ${column} at time zone 'UTC'), 'YYYY-MM-DD')`

export const getAdminOverview = createServerFn({ method: 'GET' })
  .middleware([requireAdmin])
  .handler(async () => {
    const now = new Date()
    const days = trendDays(now)
    const since = new Date(`${days[0]}T00:00:00Z`)
    const previous = new Date(since.getTime() - TREND_DAYS * DAY_MS)
    const paidDay = dayOf(payments.completedAt)
    const sentDay = dayOf(campaigns.createdAt)
    const joinedDay = dayOf(accounts.createdAt)

    const [
      [customers],
      [revenue],
      [sends],
      [pending],
      recentPayments,
      recentCampaigns,
      revenueByDay,
      sendsByDay,
      signupsByDay,
      campaignStatuses,
      bundleMix,
      topCustomers,
      [voice],
      voiceCallStatuses,
      recentVoice,
    ] = await Promise.all([
      db
        .select({
          total: sql<number>`count(*)::int`,
          recent: sql<number>`count(*) filter (where ${accounts.createdAt} >= ${since})::int`,
          previous: sql<number>`count(*) filter (where ${accounts.createdAt} >= ${previous} and ${accounts.createdAt} < ${since})::int`,
          outstandingCredits: sql<number>`coalesce(sum(${accounts.credits}), 0)::int`,
          withBalance: sql<number>`count(*) filter (where ${accounts.credits} > 0)::int`,
        })
        .from(accounts),
      db
        .select({
          total: sql<string>`coalesce(sum(${payments.amount}), 0)`,
          recent: sql<string>`coalesce(sum(${payments.amount}) filter (where ${payments.completedAt} >= ${since}), 0)`,
          previous: sql<string>`coalesce(sum(${payments.amount}) filter (where ${payments.completedAt} >= ${previous} and ${payments.completedAt} < ${since}), 0)`,
          creditsSold: sql<number>`coalesce(sum(${payments.credits}), 0)::int`,
          count: sql<number>`count(*)::int`,
          recentCount: sql<number>`count(*) filter (where ${payments.completedAt} >= ${since})::int`,
        })
        .from(payments)
        .where(eq(payments.status, 'success')),
      db
        .select({
          total: sql<number>`coalesce(sum(${campaigns.creditsUsed}), 0)::int`,
          recent: sql<number>`coalesce(sum(${campaigns.creditsUsed}) filter (where ${campaigns.createdAt} >= ${since}), 0)::int`,
          previous: sql<number>`coalesce(sum(${campaigns.creditsUsed}) filter (where ${campaigns.createdAt} >= ${previous} and ${campaigns.createdAt} < ${since}), 0)::int`,
          recipients: sql<number>`coalesce(sum(${campaigns.recipientCount}) filter (where ${campaigns.createdAt} >= ${since}), 0)::int`,
          campaigns: sql<number>`count(*)::int`,
          failed: sql<number>`count(*) filter (where ${campaigns.status} = 'failed' and ${campaigns.createdAt} >= ${since})::int`,
        })
        .from(campaigns)
        .where(eq(campaigns.channel, 'sms')),
      Promise.all([
        db.$count(senderIds, eq(senderIds.status, 'pending')),
        db.$count(payments, eq(payments.status, 'pending')),
      ]).then(([senderIdCount, paymentCount]) => [{ senderIds: senderIdCount, payments: paymentCount }]),
      db
        .select({
          reference: payments.reference,
          email: accounts.email,
          amount: payments.amount,
          credits: payments.credits,
          status: payments.status,
          createdAt: payments.createdAt,
        })
        .from(payments)
        .innerJoin(accounts, eq(accounts.userId, payments.userId))
        .orderBy(desc(payments.createdAt))
        .limit(6),
      db
        .select({
          id: campaigns.id,
          email: accounts.email,
          senderId: campaigns.senderId,
          channel: campaigns.channel,
          recipientCount: campaigns.recipientCount,
          creditsUsed: campaigns.creditsUsed,
          status: campaigns.status,
          createdAt: campaigns.createdAt,
        })
        .from(campaigns)
        .innerJoin(accounts, eq(accounts.userId, campaigns.userId))
        .orderBy(desc(campaigns.createdAt))
        .limit(6),
      db
        .select({ day: paidDay, value: sql<string>`sum(${payments.amount})` })
        .from(payments)
        .where(and(eq(payments.status, 'success'), gte(payments.completedAt, since)))
        .groupBy(paidDay),
      db
        .select({
          day: sentDay,
          value: sql<number>`coalesce(sum(${campaigns.creditsUsed}) filter (where ${campaigns.channel} = 'sms'), 0)::int`,
          voice: sql<number>`coalesce(sum(${campaigns.creditsUsed}) filter (where ${campaigns.channel} = 'voice'), 0)::int`,
        })
        .from(campaigns)
        .where(gte(campaigns.createdAt, since))
        .groupBy(sentDay),
      db
        .select({ day: joinedDay, value: sql<number>`count(*)::int` })
        .from(accounts)
        .where(gte(accounts.createdAt, since))
        .groupBy(joinedDay),
      db
        .select({ status: campaigns.status, count: sql<number>`count(*)::int` })
        .from(campaigns)
        .where(gte(campaigns.createdAt, since))
        .groupBy(campaigns.status),
      db
        .select({
          packageId: payments.packageId,
          count: sql<number>`count(*)::int`,
          amount: sql<string>`sum(${payments.amount})`,
        })
        .from(payments)
        .where(and(eq(payments.status, 'success'), gte(payments.completedAt, since)))
        .groupBy(payments.packageId),
      db
        .select({
          userId: accounts.userId,
          email: accounts.email,
          credits: accounts.credits,
          spent: sql<string>`sum(${payments.amount})`,
        })
        .from(payments)
        .innerJoin(accounts, eq(accounts.userId, payments.userId))
        .where(eq(payments.status, 'success'))
        .groupBy(accounts.userId, accounts.email, accounts.credits)
        .orderBy(desc(sql`sum(${payments.amount})`))
        .limit(5),
      db
        .select({
          total: sql<number>`coalesce(sum(${campaigns.creditsUsed}), 0)::int`,
          recent: sql<number>`coalesce(sum(${campaigns.creditsUsed}) filter (where ${campaigns.createdAt} >= ${since}), 0)::int`,
          previous: sql<number>`coalesce(sum(${campaigns.creditsUsed}) filter (where ${campaigns.createdAt} >= ${previous} and ${campaigns.createdAt} < ${since}), 0)::int`,
          sends: sql<number>`count(*) filter (where ${campaigns.createdAt} >= ${since})::int`,
          numbers: sql<number>`coalesce(sum(${campaigns.recipientCount}) filter (where ${campaigns.createdAt} >= ${since}), 0)::int`,
          customers: sql<number>`count(distinct ${campaigns.userId}) filter (where ${campaigns.createdAt} >= ${since})::int`,
        })
        .from(campaigns)
        .where(eq(campaigns.channel, 'voice')),
      db
        .select({ status: voiceCalls.status, count: sql<number>`count(*)::int` })
        .from(voiceCalls)
        .where(gte(voiceCalls.createdAt, since))
        .groupBy(voiceCalls.status),
      db
        .select({
          id: campaigns.id,
          email: accounts.email,
          message: campaigns.message,
          voice: campaigns.voice,
          recipientCount: campaigns.recipientCount,
          creditsUsed: campaigns.creditsUsed,
          status: campaigns.status,
          createdAt: campaigns.createdAt,
        })
        .from(campaigns)
        .innerJoin(accounts, eq(accounts.userId, campaigns.userId))
        .where(eq(campaigns.channel, 'voice'))
        .orderBy(desc(campaigns.createdAt))
        .limit(5),
    ])
    const recentVoiceCounts = await voiceCallCounts(recentVoice.map((c) => c.id))

    const series = (rows: { day: string; value: number | string }[]) => {
      const byDay = new Map(rows.map((r) => [r.day, Number(r.value)]))
      return days.map((day) => ({ day, value: byDay.get(day) ?? 0 }))
    }

    return {
      customers,
      revenue: {
        ...revenue,
        total: Number(revenue.total),
        recent: Number(revenue.recent),
        previous: Number(revenue.previous),
      },
      sends,
      pending,
      trends: {
        revenue: series(revenueByDay),
        sends: series(sendsByDay),
        voice: series(sendsByDay.map((r) => ({ day: r.day, value: r.voice }))),
        signups: series(signupsByDay),
      },
      campaignStatuses,
      bundleMix: bundleMix.map((b) => ({ ...b, amount: Number(b.amount) })),
      topCustomers: topCustomers.map((c) => ({ ...c, spent: Number(c.spent) })),
      recentPayments: recentPayments.map((p) => ({ ...p, amount: Number(p.amount), createdAt: p.createdAt.toISOString() })),
      recentCampaigns: recentCampaigns.map((c) => ({ ...c, createdAt: c.createdAt.toISOString() })),
      voice: {
        ...voice,
        calls: voiceCallStatuses,
        latest: recentVoice.map((c) => ({
          ...c,
          answered: recentVoiceCounts.get(c.id)?.answered ?? 0,
          missed: recentVoiceCounts.get(c.id)?.missed ?? 0,
          createdAt: c.createdAt.toISOString(),
        })),
      },
    }
  })

type BalanceResult<T> =
  | { state: 'ok'; balance: T }
  | { state: 'unconfigured'; message: string }
  | { state: 'error'; message: string }

// Balances on the provider accounts every customer send draws on: Moolre SMS
// units and the Africa's Talking voice account. Loaded separately from the
// overview so a slow provider never holds up the page.
export const getMainBalance = createServerFn({ method: 'GET' })
  .middleware([requireAdmin])
  .handler(async () => {
    const sms = async (): Promise<BalanceResult<number>> => {
      const config = await getMoolreConfig()
      if (!config.vasKey) return { state: 'unconfigured', message: 'Add the Moolre VAS key to see the SMS balance.' }
      try {
        return { state: 'ok', balance: await getSmsBalance(config) }
      } catch (error) {
        return { state: 'error', message: error instanceof Error ? error.message : 'Moolre did not return a balance.' }
      }
    }
    const voice = async (): Promise<BalanceResult<string>> => {
      const config = await getVoiceConfig()
      if (!config.username || !config.apiKey) {
        return { state: 'unconfigured', message: "Add the Africa's Talking username and API key to see the voice balance." }
      }
      try {
        const result = await probeVoice(config)
        if (!result.ok || !result.balance) return { state: 'error', message: "Africa's Talking rejected the username and API key." }
        return { state: 'ok', balance: result.balance }
      } catch {
        return { state: 'error', message: "We could not reach Africa's Talking." }
      }
    }
    const [smsBalance, voiceBalance] = await Promise.all([sms(), voice()])
    return { sms: smsBalance, voice: voiceBalance, checkedAt: new Date().toISOString() }
  })

// Small counts shown beside the admin navigation links.
export const getAdminNavCounts = createServerFn({ method: 'GET' })
  .middleware([requireAdmin])
  .handler(async () => {
    const [senderIdCount, paymentCount, chatCount] = await Promise.all([
      db.$count(senderIds, eq(senderIds.status, 'pending')),
      db.$count(payments, eq(payments.status, 'pending')),
      db.$count(chatMessages, and(eq(chatMessages.sender, 'customer'), isNull(chatMessages.readAt))),
    ])
    return { senderIds: senderIdCount, payments: paymentCount, chat: chatCount }
  })

export const getCustomers = createServerFn({ method: 'GET' })
  .middleware([requireAdmin])
  .validator(z.object({ q: z.string().trim().max(200).optional() }))
  .handler(async ({ data }) => {
    const [rows, adjustments] = await Promise.all([
      db
        .select({
          userId: accounts.userId,
          email: accounts.email,
          credits: accounts.credits,
          createdAt: accounts.createdAt,
          spent: sql<string>`(select coalesce(sum(${payments.amount}), 0) from ${payments} where ${payments.userId} = ${accounts.userId} and ${payments.status} = 'success')`,
          smsSent: sql<number>`(select coalesce(sum(${campaigns.creditsUsed}), 0) from ${campaigns} where ${campaigns.userId} = ${accounts.userId})::int`,
          lastSendAt: sql<Date | null>`(select max(${campaigns.createdAt}) from ${campaigns} where ${campaigns.userId} = ${accounts.userId})`,
        })
        .from(accounts)
        .where(data.q ? ilike(accounts.email, `%${data.q.replace(/[\\%_]/g, '\\$&')}%`) : undefined)
        .orderBy(desc(accounts.createdAt))
        .limit(200),
      db
        .select({
          id: creditAdjustments.id,
          email: accounts.email,
          amount: creditAdjustments.amount,
          reason: creditAdjustments.reason,
          adminEmail: creditAdjustments.adminEmail,
          createdAt: creditAdjustments.createdAt,
        })
        .from(creditAdjustments)
        .innerJoin(accounts, eq(accounts.userId, creditAdjustments.userId))
        .orderBy(desc(creditAdjustments.createdAt))
        .limit(20),
    ])
    return {
      customers: rows.map((r) => ({
        ...r,
        spent: Number(r.spent),
        createdAt: r.createdAt.toISOString(),
        lastSendAt: r.lastSendAt ? new Date(r.lastSendAt).toISOString() : null,
      })),
      adjustments: adjustments.map((a) => ({ ...a, createdAt: a.createdAt.toISOString() })),
    }
  })

export const adjustCredits = createServerFn({ method: 'POST' })
  .middleware([requireAdmin])
  .validator(
    z.object({
      userId: z.string().min(1),
      amount: z
        .number()
        .int()
        .refine((n) => n !== 0, 'Enter a number of credits other than zero.')
        .refine((n) => Math.abs(n) <= 1_000_000, 'That adjustment is too large.'),
      reason: z.string().trim().min(3, 'Add a short reason for the record.').max(300),
    }),
  )
  .handler(async ({ data, context }) => {
    // Removals are conditional so a balance can never go below zero.
    const [row] = await db
      .update(accounts)
      .set({ credits: sql`${accounts.credits} + ${data.amount}` })
      .where(
        data.amount < 0
          ? and(eq(accounts.userId, data.userId), sql`${accounts.credits} >= ${-data.amount}`)
          : eq(accounts.userId, data.userId),
      )
      .returning({ credits: accounts.credits, email: accounts.email })
    if (!row) {
      throw new Error(data.amount < 0 ? 'The customer does not have that many credits to remove.' : 'Customer not found.')
    }
    await db.insert(creditAdjustments).values({
      userId: data.userId,
      amount: data.amount,
      reason: data.reason,
      adminEmail: context.user.email ?? context.user.id,
    })
    const count = Math.abs(data.amount).toLocaleString()
    await notify(data.userId, {
      type: 'adjustment',
      title: data.amount > 0 ? `${count} SMS credits added to your account` : `${count} SMS credits removed from your account`,
      body: `Reason: ${data.reason.replace(/[.!?]+$/, '')}. New balance: ${row.credits.toLocaleString()} credits.`,
    })
    return row
  })

const PAYMENT_STATUSES = ['all', 'pending', 'success', 'failed'] as const

export const getAdminPayments = createServerFn({ method: 'GET' })
  .middleware([requireAdmin])
  .validator(z.object({ status: z.enum(PAYMENT_STATUSES) }))
  .handler(async ({ data }) => {
    const rows = await db
      .select({
        reference: payments.reference,
        email: accounts.email,
        packageId: payments.packageId,
        credits: payments.credits,
        amount: payments.amount,
        status: payments.status,
        payerPhone: payments.payerPhone,
        providerReference: payments.providerReference,
        createdAt: payments.createdAt,
        completedAt: payments.completedAt,
      })
      .from(payments)
      .innerJoin(accounts, eq(accounts.userId, payments.userId))
      .where(data.status === 'all' ? undefined : eq(payments.status, data.status))
      .orderBy(desc(payments.createdAt))
      .limit(200)
    return rows.map((p) => ({
      ...p,
      amount: Number(p.amount),
      createdAt: p.createdAt.toISOString(),
      completedAt: iso(p.completedAt),
    }))
  })

// Re-asks Moolre about a pending payment. settlePayment only credits once, so
// this is safe to run alongside the webhook.
export const recheckPayment = createServerFn({ method: 'POST' })
  .middleware([requireAdmin])
  .validator(z.object({ reference: z.string().min(1).max(100) }))
  .handler(async ({ data }) => {
    const payment = await settlePayment(data.reference)
    if (!payment) throw new Error('Payment not found.')
    return { status: payment.status }
  })

const CAMPAIGN_STATUSES = ['all', 'sent', 'partial', 'failed', 'sending', 'scheduled', 'cancelled'] as const

export const getAdminCampaigns = createServerFn({ method: 'GET' })
  .middleware([requireAdmin])
  .validator(z.object({ status: z.enum(CAMPAIGN_STATUSES), channel: z.enum(['all', 'sms', 'voice']).default('all') }))
  .handler(async ({ data }) => {
    const rows = await db
      .select({
        id: campaigns.id,
        email: accounts.email,
        senderId: campaigns.senderId,
        message: campaigns.message,
        recipientCount: campaigns.recipientCount,
        segments: campaigns.segments,
        creditsUsed: campaigns.creditsUsed,
        status: campaigns.status,
        channel: campaigns.channel,
        voice: campaigns.voice,
        providerResponse: campaigns.providerResponse,
        createdAt: campaigns.createdAt,
      })
      .from(campaigns)
      .innerJoin(accounts, eq(accounts.userId, campaigns.userId))
      .where(
        and(
          data.status === 'all' ? undefined : eq(campaigns.status, data.status),
          data.channel === 'all' ? undefined : eq(campaigns.channel, data.channel),
        ),
      )
      .orderBy(desc(campaigns.createdAt))
      .limit(200)
    return rows.map((c) => ({ ...c, createdAt: c.createdAt.toISOString() }))
  })

// Secrets never leave the server in full; the form only sees the last 4 characters.
function mask(value: string) {
  return value.length <= 4 ? '••••' : `••••${value.slice(-4)}`
}

export const getMoolreSettings = createServerFn({ method: 'GET' })
  .middleware([requireAdmin])
  .handler(async () => {
    const { saved, envSet, envEnvironment } = await getMoolreConfigSources()
    const savedEnvironment = saved.get('environment')
    return {
      environment: {
        value: savedEnvironment?.value === 'sandbox' ? ('sandbox' as const) : savedEnvironment ? ('live' as const) : envEnvironment,
        source: savedEnvironment ? ('dashboard' as const) : ('env' as const),
      },
      fields: MOOLRE_FIELDS.map((field) => {
        const row = saved.get(field.key)
        const source = row ? ('dashboard' as const) : envSet[field.key] ? ('env' as const) : ('none' as const)
        return {
          key: field.key,
          source,
          value: row && !field.secret ? row.value : '',
          preview: row ? (field.secret ? mask(row.value) : row.value) : null,
          // Only the account IDs inside a saved key, never the key itself.
          keyInfo: row && (field.key === 'apiPubkey' || field.key === 'vasKey') ? decodeMoolreKey(row.value) : null,
          updatedBy: row?.updatedBy ?? null,
          updatedAt: iso(row?.updatedAt ?? null),
        }
      }),
    }
  })

const fieldKey = z.enum(MOOLRE_FIELDS.map((f) => f.key) as [MoolreFieldKey, ...MoolreFieldKey[]])

export const updateMoolreSettings = createServerFn({ method: 'POST' })
  .middleware([requireAdmin])
  .validator(
    z.object({
      environment: z.enum(['live', 'sandbox']),
      // A field left out (or blank) keeps its current value; `clear` removes it.
      values: z.partialRecord(fieldKey, z.string().trim().max(500)),
      clear: z.array(fieldKey).max(MOOLRE_FIELDS.length),
    }),
  )
  .handler(async ({ data, context }) => {
    const changes: Record<string, string | null> = { environment: data.environment }
    for (const field of MOOLRE_FIELDS) {
      const value = data.values[field.key]
      if (data.clear.includes(field.key)) changes[field.key] = null
      else if (value) changes[field.key] = value
    }
    if (changes.businessEmail && !z.string().email().safeParse(changes.businessEmail).success) {
      throw new Error('Enter a valid business email.')
    }
    if (changes.senderId) {
      changes.senderId = normalizeSenderId(changes.senderId)
      if (!SENDER_ID_PATTERN.test(changes.senderId)) {
        throw new Error('The default sender ID must be 3 to 11 letters, numbers or spaces, exactly as approved on Moolre.')
      }
    }
    await saveMoolreSettings(changes, context.user.email ?? context.user.id)
    return { saved: true }
  })

type CheckState = 'ok' | 'warn' | 'fail' | 'skipped'
type ConnectionCheck = { id: 'login' | 'checkout' | 'sms' | 'sender'; state: CheckState; message: string; code: string | null }

function fieldLabel(key: MoolreFieldKey) {
  return MOOLRE_FIELDS.find((f) => f.key === key)!.label.toLowerCase()
}

function missing(config: MoolreConfig, keys: MoolreFieldKey[]) {
  const absent = keys.filter((k) => !config[k])
  return absent.length ? `Add the ${absent.map(fieldLabel).join(', ')} first.` : null
}

// Checks the form's values (unsaved ones included; blanks fall back to what is
// saved) against Moolre: the payment login, a GHS 1.00 checkout link that
// expires after a minute and is never opened, the VAS key and the sender ID.
// Nothing is charged and no message is sent.
export const checkMoolreConnection = createServerFn({ method: 'POST' })
  .middleware([requireAdmin])
  .validator(
    z.object({
      environment: z.enum(['live', 'sandbox']),
      values: z.partialRecord(fieldKey, z.string().trim().max(500)),
      clear: z.array(fieldKey).max(MOOLRE_FIELDS.length),
    }),
  )
  .handler(async ({ data }) => {
    const config: MoolreConfig = { ...(await getMoolreConfig()), environment: data.environment }
    for (const field of MOOLRE_FIELDS) {
      if (data.clear.includes(field.key)) config[field.key] = ''
      else if (data.values[field.key]) config[field.key] = data.values[field.key]!
    }
    if (config.senderId) config.senderId = normalizeSenderId(config.senderId)
    const envName = config.environment === 'sandbox' ? 'Sandbox' : 'Live'
    const other: MoolreEnvironment = config.environment === 'sandbox' ? 'live' : 'sandbox'
    const checks: ConnectionCheck[] = []
    const fail = (id: ConnectionCheck['id'], error: unknown) =>
      checks.push({ id, state: 'fail', code: null, message: error instanceof Error ? error.message : 'The check could not run.' })

    const loginMissing = missing(config, ['apiUser', 'apiPubkey', 'accountNumber'])
    let loginOk = false
    if (loginMissing) {
      checks.push({ id: 'login', state: 'skipped', code: null, message: loginMissing })
    } else {
      try {
        const login = await probePaymentLogin(config)
        loginOk = login.ok
        if (login.ok) {
          checks.push({ id: 'login', state: 'ok', code: login.code, message: `Moolre accepted the username, public key and wallet on ${envName}.` })
        } else {
          // Sandbox and Live are separate systems; say so if the other one works.
          const elsewhere = await probePaymentLogin({ ...config, environment: other }).catch(() => null)
          checks.push({
            id: 'login',
            state: 'fail',
            code: login.code,
            message: elsewhere?.ok
              ? `These are ${other === 'live' ? 'Live' : 'Sandbox'} credentials. Switch the environment to ${other === 'live' ? 'Live' : 'Sandbox'} and save.`
              : `Moolre rejected the login on ${envName}${login.message ? ` (“${login.message}”)` : ''}. Copy the API username, Public API key and wallet account number again from the same page on Moolre.`,
          })
        }
      } catch (error) {
        fail('login', error)
      }
    }

    if (!loginOk) {
      checks.push({ id: 'checkout', state: 'skipped', code: null, message: 'Runs once the login works.' })
    } else if (!config.businessEmail) {
      checks.push({ id: 'checkout', state: 'skipped', code: null, message: `Add the ${fieldLabel('businessEmail')} first.` })
    } else {
      const origin = getRequestUrl().origin
      const reference = `TEST-${Date.now().toString(36).toUpperCase()}-${crypto.randomUUID().slice(0, 8).toUpperCase()}`
      try {
        await createPaymentLink(
          {
            amount: 1,
            reference,
            callbackUrl: `${origin}/api/moolre/webhook`,
            redirectUrl: `${origin}/admin/settings`,
            metadata: { reference, test: 'admin' },
            expirationMinutes: 1,
          },
          config,
        )
        checks.push({ id: 'checkout', state: 'ok', code: 'POS09', message: 'Moolre created a test payment link. Customers can buy credit.' })
      } catch (error) {
        const detail = error instanceof MoolreError && error.detail ? ` Moolre said: “${error.detail}”.` : ''
        checks.push({
          id: 'checkout',
          state: 'fail',
          code: error instanceof MoolreError ? error.code : null,
          message: `${error instanceof Error ? error.message : 'The test failed.'}${detail}`,
        })
      }
    }

    if (!config.vasKey) {
      checks.push({ id: 'sms', state: 'skipped', code: null, message: `Add the ${fieldLabel('vasKey')} first.` })
      checks.push({ id: 'sender', state: 'skipped', code: null, message: 'Runs once the VAS key is added.' })
    } else {
      try {
        const sms = await probeSms(config, config.senderId)
        if (sms.code?.startsWith('AIN')) {
          checks.push({ id: 'sms', state: 'fail', code: sms.code, message: `Moolre rejected the VAS key on ${envName}. Copy the SMS API key again from Moolre.` })
          checks.push({ id: 'sender', state: 'skipped', code: null, message: 'Runs once the VAS key works.' })
        } else {
          checks.push({ id: 'sms', state: 'ok', code: sms.code, message: `Moolre accepted the VAS key on ${envName}.` })
          if (!config.senderId) {
            checks.push({
              id: 'sender',
              state: 'warn',
              code: null,
              message: 'No default sender ID. Customers can only send with sender IDs you approve for them.',
            })
          } else if (!SENDER_ID_PATTERN.test(config.senderId)) {
            checks.push({ id: 'sender', state: 'fail', code: null, message: `“${config.senderId}” is not valid. Use 3 to 11 letters, numbers or spaces.` })
          } else if (sms.code === 'ASMS07') {
            checks.push({
              id: 'sender',
              state: 'fail',
              code: sms.code,
              message: `Moolre has not approved “${config.senderId}”. Register it under Sender IDs on app.moolre.com and wait for approval.`,
            })
          } else {
            checks.push({ id: 'sender', state: 'ok', code: sms.code, message: `Moolre accepted the sender ID “${config.senderId}”.` })
          }
        }
      } catch (error) {
        fail('sms', error)
      }
    }

    return { environment: config.environment, checkedAt: new Date().toISOString(), checks }
  })

// Africa's Talking settings for voice SMS, shown under the Moolre settings.
export const getVoiceSettings = createServerFn({ method: 'GET' })
  .middleware([requireAdmin])
  .handler(async () => {
    const { saved, envSet } = await getVoiceConfigSources()
    return {
      fields: VOICE_FIELDS.map((field) => {
        const row = saved.get(field.key)
        return {
          key: field.key,
          source: row ? ('dashboard' as const) : envSet[field.key] ? ('env' as const) : ('none' as const),
          value: row && !field.secret ? row.value : '',
          preview: row ? (field.secret ? mask(row.value) : row.value) : null,
          updatedBy: row?.updatedBy ?? null,
          updatedAt: iso(row?.updatedAt ?? null),
        }
      }),
    }
  })

const voiceFieldKey = z.enum(VOICE_FIELDS.map((f) => f.key) as [VoiceFieldKey, ...VoiceFieldKey[]])
const voiceSettingsInput = z.object({
  values: z.partialRecord(voiceFieldKey, z.string().trim().max(500)),
  clear: z.array(voiceFieldKey).max(VOICE_FIELDS.length),
})

export const updateVoiceSettings = createServerFn({ method: 'POST' })
  .middleware([requireAdmin])
  .validator(voiceSettingsInput)
  .handler(async ({ data, context }) => {
    const changes: Record<string, string | null> = {}
    for (const field of VOICE_FIELDS) {
      const value = data.values[field.key]
      if (data.clear.includes(field.key)) changes[field.key] = null
      else if (value) changes[field.key] = value
    }
    if (changes.phoneNumber) {
      changes.phoneNumber = changes.phoneNumber.replace(/[\s()-]/g, '')
      if (!/^\+\d{8,15}$/.test(changes.phoneNumber)) throw new Error('Enter the voice number in international format, e.g. +233302000000.')
    }
    await saveVoiceSettings(changes, context.user.email ?? context.user.id)
    return { saved: true }
  })

// Checks the form's values (blanks fall back to what is saved) by reading the
// Africa's Talking balance. No call is placed.
export const checkVoiceConnection = createServerFn({ method: 'POST' })
  .middleware([requireAdmin])
  .validator(voiceSettingsInput)
  .handler(async ({ data }) => {
    const config: VoiceConfig = { ...(await getVoiceConfig()) }
    for (const field of VOICE_FIELDS) {
      if (data.clear.includes(field.key)) config[field.key] = ''
      else if (data.values[field.key]) config[field.key] = data.values[field.key]!
    }
    const absent = VOICE_FIELDS.filter((f) => !config[f.key]).map((f) => f.label.toLowerCase())
    if (!config.username || !config.apiKey) {
      return { state: 'skipped' as const, message: `Add the ${absent.join(', ')} first.` }
    }
    try {
      const result = await probeVoice(config)
      if (!result.ok) {
        return {
          state: 'fail' as const,
          message: `Africa's Talking rejected the username and API key${result.detail ? ` (“${result.detail}”)` : ''}. Generate a new API key for this app and try again.`,
        }
      }
      if (!config.phoneNumber) {
        return { state: 'warn' as const, message: `Login works (balance ${result.balance}). Add the voice phone number to start calling.` }
      }
      return { state: 'ok' as const, message: `Africa's Talking accepted the login. Account balance: ${result.balance}.` }
    } catch (error) {
      return { state: 'fail' as const, message: error instanceof Error ? error.message : 'The check could not run.' }
    }
  })

// Automatic sign-in and purchase texts: wording, on/off, and what went out.
export const getAutoSmsAdmin = createServerFn({ method: 'GET' })
  .middleware([requireAdmin])
  .handler(async () => {
    const [settings, recent, [{ withPhone }], config] = await Promise.all([
      getAutoSmsSettings(),
      recentAutoMessages(),
      db
        .select({ withPhone: sql<number>`count(*)::int` })
        .from(accounts)
        .where(and(sql`${accounts.phone} is not null`, eq(accounts.smsAlerts, true))),
      getMoolreConfig(),
    ])
    return {
      senderId: config.senderId || null,
      customersWithPhone: withPhone,
      events: AUTO_SMS_EVENTS.map((e) => ({
        key: e.key,
        enabled: settings[e.key].enabled,
        template: settings[e.key].template,
        updatedBy: settings[e.key].updatedBy,
        updatedAt: iso(settings[e.key].updatedAt),
      })),
      recent: recent.map((m) => ({ ...m, createdAt: m.createdAt.toISOString() })),
    }
  })

const autoSmsEvent = z.enum(AUTO_SMS_EVENTS.map((e) => e.key) as [AutoSmsEvent, ...AutoSmsEvent[]])
const autoSmsTemplate = z.string().trim().min(1, 'Write the message first.').max(AUTO_SMS_MAX_LENGTH)

export const updateAutoSms = createServerFn({ method: 'POST' })
  .middleware([requireAdmin])
  .validator(z.object({ event: autoSmsEvent, enabled: z.boolean(), template: autoSmsTemplate }))
  .handler(async ({ data, context }) => {
    await saveAutoSmsSetting(data.event, { enabled: data.enabled, template: data.template }, context.user.email ?? context.user.id)
    return { saved: true }
  })

// Sends the unsaved template, filled with sample values, to a number the admin types.
export const sendAutoSmsTest = createServerFn({ method: 'POST' })
  .middleware([requireAdmin])
  .validator(z.object({ event: autoSmsEvent, template: autoSmsTemplate, phone: z.string().trim().max(30) }))
  .handler(async ({ data, context }) => {
    const phone = normalizeGhanaPhone(data.phone)
    if (!phone) throw new Error('Enter a Ghana number, e.g. 024 123 4567.')
    await ensureAccount(context.user)
    const result = await deliverAutoSms(context.user.id, 'test', phone, renderAutoSms(data.template, sampleValues(data.event)))
    if (!result.ok) throw new Error(result.error ?? 'The test text could not be sent.')
    return { sent: true }
  })

// Gmail settings for emailed purchase receipts, shown on /admin/settings.
export const getEmailSettings = createServerFn({ method: 'GET' })
  .middleware([requireAdmin])
  .handler(async () => {
    const [{ saved, envSet, receiptsEnabled }, recent, config] = await Promise.all([
      getEmailConfigSources(),
      recentEmails(),
      getEmailConfig(),
    ])
    return {
      address: config.address,
      ready: Boolean(config.address && config.appPassword),
      receiptsEnabled,
      fields: EMAIL_FIELDS.map((field) => {
        const row = saved.get(field.key)
        return {
          key: field.key,
          source: row ? ('dashboard' as const) : envSet[field.key] ? ('env' as const) : ('none' as const),
          value: row && !field.secret ? row.value : '',
          preview: row ? (field.secret ? mask(row.value) : row.value) : null,
          updatedBy: row?.updatedBy ?? null,
          updatedAt: iso(row?.updatedAt ?? null),
        }
      }),
      recent: recent.map((m) => ({ ...m, createdAt: m.createdAt.toISOString() })),
    }
  })

const emailFieldKey = z.enum(EMAIL_FIELDS.map((f) => f.key) as [EmailFieldKey, ...EmailFieldKey[]])
const emailSettingsInput = z.object({
  values: z.partialRecord(emailFieldKey, z.string().trim().max(500)),
  clear: z.array(emailFieldKey).max(EMAIL_FIELDS.length),
})

function emailChanges(data: z.infer<typeof emailSettingsInput>) {
  const changes: Record<string, string | null> = {}
  for (const field of EMAIL_FIELDS) {
    const value = data.values[field.key]
    if (data.clear.includes(field.key)) changes[field.key] = null
    else if (value) changes[field.key] = field.key === 'appPassword' ? value.replace(/\s+/g, '') : value
  }
  if (changes.address && !z.email().safeParse(changes.address).success) throw new Error('Enter a valid Gmail address.')
  if (changes.appPassword && !/^[a-z]{16}$/i.test(changes.appPassword)) {
    throw new Error('A Gmail app password is 16 letters, e.g. abcd efgh ijkl mnop. Your normal Gmail password won’t work.')
  }
  return changes
}

// The form's values on top of what is saved, for checks and tests before saving.
async function emailConfigWith(data: z.infer<typeof emailSettingsInput>): Promise<EmailConfig> {
  const config = { ...(await getEmailConfig()) }
  const changes = emailChanges(data)
  for (const field of EMAIL_FIELDS) {
    if (changes[field.key] !== undefined) config[field.key] = changes[field.key] ?? ''
  }
  return config
}

export const updateEmailSettings = createServerFn({ method: 'POST' })
  .middleware([requireAdmin])
  .validator(emailSettingsInput)
  .handler(async ({ data, context }) => {
    await saveEmailSettings(emailChanges(data), context.user.email ?? context.user.id)
    return { saved: true }
  })

export const updateEmailReceipts = createServerFn({ method: 'POST' })
  .middleware([requireAdmin])
  .validator(z.object({ enabled: z.boolean() }))
  .handler(async ({ data, context }) => {
    await setReceiptsEnabled(data.enabled, context.user.email ?? context.user.id)
    return { saved: true }
  })

// Logs in to Gmail with the form's values (blanks fall back to what is saved). Nothing is sent.
export const checkEmailConnection = createServerFn({ method: 'POST' })
  .middleware([requireAdmin])
  .validator(emailSettingsInput)
  .handler(async ({ data }) => {
    const config = await emailConfigWith(data)
    if (!config.address || !config.appPassword) {
      return { state: 'skipped' as const, message: 'Add the Gmail address and app password first.' }
    }
    const result = await probeEmail(config)
    if (!result.ok) return { state: 'fail' as const, message: result.error ?? 'Gmail rejected the login.' }
    return { state: 'ok' as const, message: `Gmail accepted the login. Receipts will be sent from ${config.address}.` }
  })

// Emails a sample receipt to an address the admin types, using the form's values.
export const sendTestReceipt = createServerFn({ method: 'POST' })
  .middleware([requireAdmin])
  .validator(emailSettingsInput.extend({ to: z.email('Enter a valid email address.') }))
  .handler(async ({ data, context }) => {
    const config = await emailConfigWith(data)
    if (!config.address || !config.appPassword) throw new Error('Add the Gmail address and app password first.')
    await ensureAccount(context.user)
    const result = await deliverEmail(context.user.id, 'test', buildReceipt({ ...SAMPLE_RECEIPT, date: new Date() }, data.to), null, config)
    if (!result.ok) throw new Error(result.error ?? 'The test email could not be sent.')
    return { sent: true }
  })

// Labels for Moolre's per-message delivery status numbers, shown on
// /admin/settings with how often each number came back in the last 30 days.
export const getDeliverySettings = createServerFn({ method: 'GET' })
  .middleware([requireAdmin])
  .handler(async () => {
    const [labels, seen] = await Promise.all([getDeliveryLabels(), recentDeliveryCodes().catch(() => [])])
    const counts = new Map(seen.map((s) => [s.code, s.count]))
    const codes = [...new Set([...DELIVERY_CODES, ...seen.map((s) => s.code)])].filter((c) => DELIVERY_CODES.includes(c)).sort((a, b) => a - b)
    return {
      codes: codes.map((code) => ({ code, label: labels.get(code) ?? null, seen: counts.get(code) ?? 0 })),
      unlisted: seen.filter((s) => !DELIVERY_CODES.includes(s.code)),
    }
  })

const deliveryLabel = z.enum(['delivered', 'failed', 'pending']).nullable()

export const updateDeliveryLabels = createServerFn({ method: 'POST' })
  .middleware([requireAdmin])
  .validator(z.object({ labels: z.record(z.string().regex(/^\d$/), deliveryLabel) }))
  .handler(async ({ data, context }) => {
    const changes = Object.fromEntries(Object.entries(data.labels).map(([code, value]) => [Number(code), value]))
    await saveDeliveryLabels(changes, context.user.email ?? context.user.id)
    return { saved: true }
  })
