// Server-only Moolre client. Payments use the hosted payment link (cards and
// mobile money), confirmed through the status endpoint. SMS uses the VAS API.
// Credentials come from /admin/settings, falling back to environment variables.
import { eq, like } from 'drizzle-orm'
import { z } from 'zod'
import { db } from '../../db/index.js'
import { appSettings } from '../../db/schema.js'
import { MOOLRE_FIELDS, type MoolreEnvironment, type MoolreFieldKey } from './moolre-settings'

const envelope = z.object({
  status: z.union([z.number(), z.string()]),
  code: z.string().nullish(),
  message: z.string().nullish(),
  data: z.unknown(),
})

const SETTING_PREFIX = 'moolre.'
const CACHE_MS = 30_000

export type MoolreConfig = Record<MoolreFieldKey, string> & { environment: MoolreEnvironment }

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

async function savedSettings() {
  if (cached && Date.now() - cached.at < CACHE_MS) return cached.values
  const rows = await db
    .select({ key: appSettings.key, value: appSettings.value })
    .from(appSettings)
    .where(like(appSettings.key, `${SETTING_PREFIX}%`))
  const values = new Map(rows.map((r) => [r.key.slice(SETTING_PREFIX.length), r.value]))
  cached = { at: Date.now(), values }
  return values
}

// Values saved in the admin console win; environment variables are the fallback.
export async function getMoolreConfig(): Promise<MoolreConfig> {
  const saved = await savedSettings()
  const config = {} as MoolreConfig
  for (const field of MOOLRE_FIELDS) config[field.key] = (saved.get(field.key) || process.env[field.env] || '').trim()
  const environment = saved.get('environment') || process.env.MOOLRE_ENV
  config.environment = environment === 'sandbox' ? 'sandbox' : 'live'
  return config
}

// Where each value currently comes from, for the settings page. Always reads fresh.
export async function getMoolreConfigSources() {
  const rows = await db
    .select()
    .from(appSettings)
    .where(like(appSettings.key, `${SETTING_PREFIX}%`))
  return {
    saved: new Map(rows.map((r) => [r.key.slice(SETTING_PREFIX.length), r])),
    envSet: Object.fromEntries(MOOLRE_FIELDS.map((f) => [f.key, Boolean(process.env[f.env])])) as Record<MoolreFieldKey, boolean>,
    envEnvironment: (process.env.MOOLRE_ENV === 'sandbox' ? 'sandbox' : 'live') as MoolreEnvironment,
  }
}

// Saves (or clears, when the value is null) Moolre settings.
export async function saveMoolreSettings(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
}

function baseUrl(config: MoolreConfig) {
  return config.environment === 'sandbox' ? 'https://sandbox.moolre.com' : 'https://api.moolre.com'
}

function required(config: MoolreConfig, key: MoolreFieldKey) {
  const value = config[key]
  if (!value) {
    const field = MOOLRE_FIELDS.find((f) => f.key === key)!
    throw new Error(`Moolre is not configured yet (missing ${field.label}).`)
  }
  return value
}

function paymentHeaders(config: MoolreConfig) {
  return {
    'Content-Type': 'application/json',
    'X-API-USER': required(config, 'apiUser'),
    'X-API-PUBKEY': required(config, 'apiPubkey'),
  }
}

async function post(config: MoolreConfig, path: string, headers: Record<string, string>, body: unknown) {
  let res: Response
  try {
    res = await fetch(`${baseUrl(config)}${path}`, {
      method: 'POST',
      headers,
      body: JSON.stringify(body),
      signal: AbortSignal.timeout(20_000),
    })
  } catch (error) {
    console.error('Moolre request failed', path, error)
    throw new Error('We could not reach Moolre. Please try again in a moment.', { cause: error })
  }
  let json: unknown
  try {
    json = await res.json()
  } catch {
    throw new Error(`Moolre returned an unreadable response (${res.status}).`)
  }
  const parsed = envelope.safeParse(json)
  if (!parsed.success) throw new Error(`Moolre returned an unexpected response (${res.status}).`)
  return { httpStatus: res.status, ...parsed.data }
}

// Thrown when Moolre answers but refuses the request. The message is safe to
// show to customers; code and detail are Moolre's own, for admins and logs.
export class MoolreError extends Error {
  constructor(
    message: string,
    readonly code: string | null,
    readonly detail: string | null,
  ) {
    super(message)
  }
}

const linkData = z.object({
  authorization_url: z.string().min(1),
  reference: z.union([z.string(), z.number()]).nullish(),
})

// Sandbox and Live are separate Moolre systems: credentials from one are
// unknown to the other, which shows up as an AIN (authentication) code.
function credentialHint(environment: MoolreEnvironment) {
  return environment === 'sandbox'
    ? ' The environment is set to Sandbox, which needs sandbox credentials. If these are your live Moolre credentials, switch the environment to Live.'
    : ' The environment is set to Live. If these are sandbox credentials, switch the environment to Sandbox.'
}

function paymentLinkFailure(code: string | null | undefined, message: string | null | undefined, environment: MoolreEnvironment) {
  const reason =
    code === 'AIN12'
      ? `Moolre does not recognise the API username.${credentialHint(environment)}`
      : code?.startsWith('AIN')
      ? `Moolre rejected the payment credentials (API username, public key or wallet account number).${credentialHint(environment)}`
      : code === 'INP02' || code === 'TP13'
        ? 'Moolre already has a payment with this reference.'
        : code === 'TP01' || code === 'APGW06'
          ? 'The Moolre wallet does not accept GHS payments through the API.'
          : code === 'TP09'
            ? 'The Moolre wallet is not enabled for payment links.'
            : message?.trim() || 'Moolre did not return a payment link.'
  const suffix = code ? ` (Moolre code ${code})` : ''
  return new MoolreError(`We could not start the payment: ${reason}${suffix}`, code ?? null, message ?? null)
}

export async function createPaymentLink(input: {
  amount: number
  reference: string
  callbackUrl: string
  redirectUrl: string
  metadata: Record<string, string>
  expirationMinutes?: number
}, config?: MoolreConfig) {
  config ??= await getMoolreConfig()
  const result = await post(config, '/embed/link', paymentHeaders(config), {
    type: 1,
    amount: input.amount.toFixed(2),
    email: required(config, 'businessEmail'),
    externalref: input.reference,
    callback: input.callbackUrl,
    redirect: input.redirectUrl,
    reusable: '0',
    currency: 'GHS',
    accountnumber: required(config, 'accountNumber'),
    expiration_time: input.expirationMinutes ?? 60,
    metadata: input.metadata,
  })
  const data = linkData.safeParse(result.data)
  if (result.code !== 'POS09' || !data.success) {
    console.error('Moolre payment link failed', config.environment, result.httpStatus, result.code, result.message, JSON.stringify(result.data))
    throw paymentLinkFailure(result.code, result.message, config.environment)
  }
  return {
    url: data.data.authorization_url,
    providerReference: data.data.reference != null ? String(data.data.reference) : null,
  }
}

// Harmless checks for the admin settings page. Neither charges anything or
// sends a message: the status lookup asks about a reference that doesn't exist
// (Moolre answers SS07 once the login works) and the SMS request is empty.
export async function probePaymentLogin(config: MoolreConfig) {
  const result = await post(config, '/open/transact/status', paymentHeaders(config), {
    type: 1,
    idtype: 1,
    id: `CHECK-${Date.now().toString(36).toUpperCase()}`,
    accountnumber: required(config, 'accountNumber'),
  })
  return { ok: !result.code?.startsWith('AIN'), code: result.code ?? null, message: result.message ?? null }
}

export async function probeSms(config: MoolreConfig, senderId: string) {
  const result = await post(
    config,
    '/open/sms/send',
    { 'Content-Type': 'application/json', 'X-API-VASKEY': required(config, 'vasKey') },
    { type: 1, senderid: senderId, messages: [] },
  )
  return { code: result.code ?? null, message: result.message ?? null }
}

export type PaymentStatus = 'success' | 'pending' | 'failed'

export async function checkPaymentStatus(reference: string) {
  const config = await getMoolreConfig()
  const result = await post(config, '/open/transact/status', paymentHeaders(config), {
    type: 1,
    idtype: 1,
    id: reference,
    accountnumber: required(config, 'accountNumber'),
  })
  const data = z
    .object({
      txstatus: z.coerce.number(),
      amount: z.coerce.number().nullish(),
      transactionid: z.union([z.string(), z.number()]).nullish(),
      payer: z.string().nullish(),
    })
    .safeParse(result.data)
  if (result.code !== 'SS01' || !data.success) return { status: 'pending' as PaymentStatus }
  const status: PaymentStatus =
    data.data.txstatus === 1 ? 'success' : data.data.txstatus === 2 ? 'failed' : 'pending'
  return {
    status,
    amount: data.data.amount ?? null,
    transactionId: data.data.transactionid != null ? String(data.data.transactionid) : null,
    payer: data.data.payer ?? null,
  }
}

export async function sendSmsBatch(input: {
  senderId: string
  messages: { recipient: string; message: string; ref: string }[]
}) {
  const config = await getMoolreConfig()
  const result = await post(
    config,
    '/open/sms/send',
    { 'Content-Type': 'application/json', 'X-API-VASKEY': required(config, 'vasKey') },
    { type: 1, senderid: input.senderId, messages: input.messages },
  )
  if (result.code === 'SMS01') return { ok: true as const }
  console.error('Moolre SMS send failed', result.httpStatus, result.code, result.message)
  const reason =
    result.code === 'ASMS07'
      ? `Sender ID "${input.senderId}" was refused by the SMS provider. Contact support; unsent messages are refunded.`
      : result.code?.startsWith('AIN')
        ? 'The SMS service rejected our credentials.'
        : 'The SMS service could not accept these messages.'
  return { ok: false as const, code: result.code ?? 'unknown', reason }
}

// The SMS units left on the Moolre VAS account. Every customer send draws on it.
export async function getSmsBalance(config?: MoolreConfig) {
  config ??= await getMoolreConfig()
  const result = await post(
    config,
    '/open/sms/status',
    { 'Content-Type': 'application/json', 'X-API-VASKEY': required(config, 'vasKey') },
    { type: 2 },
  )
  const data = z.object({ balance: z.coerce.number() }).safeParse(result.data)
  if (result.code !== 'ASMQ03' || !data.success) {
    console.error('Moolre SMS balance failed', result.httpStatus, result.code, result.message)
    throw new MoolreError(
      result.code?.startsWith('AIN') ? 'Moolre rejected the VAS key.' : result.message?.trim() || 'Moolre did not return a balance.',
      result.code ?? null,
      result.message ?? null,
    )
  }
  return data.data.balance
}

// Delivery status of sent messages, looked up by the `ref` each message was
// sent with (type 5). Moolre answers ASMQ10 with one { ref, status } per ref it
// knows. Its docs don't say what each status number means, so callers map
// them through the labels admins set on /admin/settings (see delivery.server.ts).
export const SMS_STATUS_BATCH = 100

export async function getSmsStatuses(refs: string[], config?: MoolreConfig) {
  config ??= await getMoolreConfig()
  const result = await post(
    config,
    '/open/sms/status',
    { 'Content-Type': 'application/json', 'X-API-VASKEY': required(config, 'vasKey') },
    { type: 5, ref: refs },
  )
  const rows = z
    .array(z.object({ ref: z.union([z.string(), z.number()]), status: z.coerce.number() }))
    .safeParse(result.data)
  if (result.code !== 'ASMQ10' || !rows.success) {
    console.error('Moolre SMS status failed', result.httpStatus, result.code, result.message)
    throw new MoolreError(
      result.code?.startsWith('AIN') ? 'Moolre rejected the VAS key.' : result.message?.trim() || 'Moolre did not return delivery statuses.',
      result.code ?? null,
      result.message ?? null,
    )
  }
  return new Map(rows.data.map((r) => [String(r.ref), r.status]))
}
