// Server-only automatic texts (sign-in and purchase). Sent from the platform
// sender ID and paid for by the platform, not the customer's credits.
import { desc, eq, like } from 'drizzle-orm'
import { db } from '../../db/index.js'
import { accounts, appSettings, autoMessages } from '../../db/schema.js'
import { AUTO_SMS_EVENTS, renderAutoSms, type AutoSmsEvent } from './auto-sms'
import { getMoolreConfig, sendSmsBatch } from './moolre.server'
import { normalizeGhanaPhone } from './sms'

const PREFIX = 'autosms.'

export type AutoSmsSetting = { enabled: boolean; template: string; updatedBy: string | null; updatedAt: Date | null }

export async function getAutoSmsSettings() {
  const rows = await db.select().from(appSettings).where(like(appSettings.key, `${PREFIX}%`))
  const saved = new Map(rows.map((r) => [r.key.slice(PREFIX.length), r]))
  return Object.fromEntries(
    AUTO_SMS_EVENTS.map((e) => {
      const enabled = saved.get(`${e.key}.enabled`)
      const template = saved.get(`${e.key}.template`)
      const latest = [enabled, template].filter(Boolean).sort((a, b) => +b!.updatedAt - +a!.updatedAt)[0]
      return [
        e.key,
        {
          enabled: enabled ? enabled.value === 'true' : true,
          template: template?.value || e.defaultTemplate,
          updatedBy: latest?.updatedBy ?? null,
          updatedAt: latest?.updatedAt ?? null,
        },
      ]
    }),
  ) as Record<AutoSmsEvent, AutoSmsSetting>
}

export async function saveAutoSmsSetting(event: AutoSmsEvent, setting: { enabled: boolean; template: string }, updatedBy: string) {
  const values = { enabled: String(setting.enabled), template: setting.template }
  for (const [name, value] of Object.entries(values)) {
    const key = `${PREFIX}${event}.${name}`
    await db
      .insert(appSettings)
      .values({ key, value, updatedBy })
      .onConflictDoUpdate({ target: appSettings.key, set: { value, updatedBy, updatedAt: new Date() } })
  }
}

// Sends one text and logs it. Returns the outcome; never throws.
export async function deliverAutoSms(userId: string, event: AutoSmsEvent | 'test', phone: string, message: string) {
  let error: string | null = null
  try {
    const { senderId } = await getMoolreConfig()
    if (!senderId) error = 'No default sender ID is set in the Moolre settings.'
    else {
      const result = await sendSmsBatch({ senderId, messages: [{ recipient: phone, message, ref: `A${event}-${Date.now()}` }] })
      if (!result.ok) error = result.reason
    }
  } catch (err) {
    error = err instanceof Error ? err.message : 'The SMS service is unavailable.'
  }
  try {
    await db.insert(autoMessages).values({ userId, event, phone, message, status: error ? 'failed' : 'sent', error })
  } catch (err) {
    console.error('Could not log automatic SMS', err)
  }
  return { ok: !error, error }
}

// Sends the automatic text for `event` if it is switched on and the customer
// has a phone number and hasn't turned texts off. `fallbackPhone` (e.g. the
// mobile money number that paid) is used when no number is saved.
export async function sendAutoSms(
  userId: string,
  event: AutoSmsEvent,
  values: Record<string, string>,
  fallbackPhone?: string | null,
) {
  try {
    const [settings, [account]] = await Promise.all([
      getAutoSmsSettings(),
      db
        .select({ name: accounts.name, email: accounts.email, credits: accounts.credits, phone: accounts.phone, smsAlerts: accounts.smsAlerts })
        .from(accounts)
        .where(eq(accounts.userId, userId)),
    ])
    const setting = settings[event]
    if (!setting.enabled || !account || !account.smsAlerts) return
    const phone = account.phone ?? (fallbackPhone ? normalizeGhanaPhone(fallbackPhone) : null)
    if (!phone) return
    const message = renderAutoSms(setting.template, {
      name: account.name?.trim().split(/\s+/)[0] || 'there',
      email: account.email,
      balance: account.credits.toLocaleString('en-GH'),
      ...values,
    })
    await deliverAutoSms(userId, event, phone, message)
  } catch (error) {
    console.error('Automatic SMS failed', event, error)
  }
}

export async function recentAutoMessages(limit = 20) {
  return db
    .select({
      id: autoMessages.id,
      event: autoMessages.event,
      phone: autoMessages.phone,
      message: autoMessages.message,
      status: autoMessages.status,
      error: autoMessages.error,
      createdAt: autoMessages.createdAt,
      email: accounts.email,
    })
    .from(autoMessages)
    .innerJoin(accounts, eq(accounts.userId, autoMessages.userId))
    .orderBy(desc(autoMessages.createdAt))
    .limit(limit)
}

export function ghanaTime(date = new Date()) {
  return new Intl.DateTimeFormat('en-GB', { timeZone: 'Africa/Accra', day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' }).format(date)
}
