// Server-only sending logic shared by the dashboard composer, the public SMS
// API and the scheduled-send job, so all apply the same sender ID, cost and
// refund rules.
//
// A send is created (checked, charged, recorded) and then dispatched in
// batches of 100. Dispatch saves its place after every batch, so a send that
// runs out of time continues where it stopped: immediate sends hold a short
// lease while their request is sending, and the every-minute job
// (netlify/functions/send-scheduled.mts) sends due scheduled sends and picks up
// any send whose lease expired mid-way.
import { and, asc, eq, isNotNull, lt, lte, sql } from 'drizzle-orm'
import { db } from '../../db/index.js'
import { accounts, campaigns, senderIds } from '../../db/schema.js'
import { refundCredits, spendCredits } from './billing.server'
import { getMoolreConfig, sendSmsBatch } from './moolre.server'
import { countSegments } from './sms'

export const MAX_RECIPIENTS = 5_000
export const MAX_SEGMENTS = 6
const BATCH_SIZE = 100
// Scheduled sends must be at least a couple of minutes ahead and at most 60 days.
export const MIN_SCHEDULE_LEAD_MS = 2 * 60_000
export const MAX_SCHEDULE_AHEAD_MS = 60 * 24 * 60 * 60_000
// How long a sender may go without saving progress before another run takes over.
const LEASE_MS = 2 * 60_000
// Never resume a send older than this; something is wrong and it needs a person.
const RESUME_MAX_AGE_MS = 24 * 60 * 60_000

// The `ref` each message is sent with. Delivery statuses are looked up by it.
export function messageRef(campaignId: number, index: number) {
  return `C${campaignId}-${index}`
}

// A send that was refused before or during delivery. `code` and `status` are
// returned as-is by the public API.
export class SendError extends Error {
  constructor(
    message: string,
    readonly code: string,
    readonly status: number,
  ) {
    super(message)
  }
}

export async function platformSenderId() {
  return (await getMoolreConfig()).senderId
}

// Customers can only send with sender IDs they requested and an admin
// approved. The platform sender ID is reserved for automatic texts.
export async function isSenderIdAllowed(userId: string, senderId: string) {
  const [row] = await db
    .select({ id: senderIds.id })
    .from(senderIds)
    .where(
      and(
        eq(senderIds.userId, userId),
        eq(senderIds.status, 'approved'),
        sql`lower(${senderIds.senderId}) = lower(${senderId})`,
      ),
    )
  return Boolean(row)
}

// Sender IDs this user can send with right now.
export async function usableSenderIds(userId: string) {
  const rows = await db
    .select({ senderId: senderIds.senderId })
    .from(senderIds)
    .where(and(eq(senderIds.userId, userId), eq(senderIds.status, 'approved')))
  return rows.map((r) => r.senderId)
}

type SendInput = {
  userId: string
  senderId: string
  message: string
  recipients: string[]
  source: 'dashboard' | 'api'
}

// Checks the send, deducts its credits and records it. `recipients` must
// already be normalized and de-duplicated.
async function createCampaign(input: SendInput & { scheduledFor: Date | null }) {
  const { userId, senderId, message, recipients } = input
  if (!(await isSenderIdAllowed(userId, senderId))) {
    throw new SendError(
      `The sender ID “${senderId}” has not been approved for your account yet.`,
      'sender_id_not_approved',
      403,
    )
  }
  if (recipients.length === 0) throw new SendError('Add at least one valid Ghana phone number.', 'no_valid_recipients', 422)
  if (recipients.length > MAX_RECIPIENTS) {
    throw new SendError(`You can send to at most ${MAX_RECIPIENTS} numbers at once.`, 'too_many_recipients', 422)
  }

  const { segments } = countSegments(message)
  if (segments > MAX_SEGMENTS) throw new SendError('Messages can be at most 6 SMS parts long.', 'message_too_long', 422)
  const cost = recipients.length * segments

  if (!(await spendCredits(userId, cost))) {
    throw new SendError(
      `You need ${cost.toLocaleString()} credits for this send. Top up your balance first.`,
      'insufficient_credits',
      402,
    )
  }

  const [campaign] = await db
    .insert(campaigns)
    .values({
      userId,
      senderId,
      message,
      recipients,
      recipientCount: recipients.length,
      segments,
      creditsUsed: cost,
      source: input.source,
      status: input.scheduledFor ? 'scheduled' : 'sending',
      scheduledFor: input.scheduledFor,
      // Immediate sends start sending now, so they hold the lease from the start.
      lockedUntil: input.scheduledFor ? null : new Date(Date.now() + LEASE_MS),
    })
    .returning({ id: campaigns.id })
  return { id: campaign.id, cost, segments }
}

export type DispatchResult = {
  id: number
  done: boolean
  status: 'sending' | 'sent' | 'partial' | 'failed'
  delivered: number
  total: number
  segments: number
  creditsUsed: number
  error: string | null
}

// Marks recipient indexes as never sent (-1) in the delivery map.
function notSentPatch(from: number, to: number) {
  const patch: Record<string, number> = {}
  for (let i = from; i < to; i++) patch[i] = -1
  return patch
}

// Sends the campaign's remaining batches, saving progress after each one,
// until it finishes or `deadline` passes. The caller must hold the lease.
export async function dispatchCampaign(campaignId: number, opts: { deadline?: number } = {}): Promise<DispatchResult> {
  const [c] = await db.select().from(campaigns).where(eq(campaigns.id, campaignId))
  if (!c) throw new Error(`Campaign ${campaignId} not found`)
  const total = c.recipientCount
  let progress = c.sendProgress
  let sent = c.sentCount
  let lastError = c.providerResponse
  let stopped = false

  // A scheduled send re-checks its sender ID when it starts, since an admin
  // may have revoked it after the send was booked.
  if (progress === 0 && c.scheduledFor && !(await isSenderIdAllowed(c.userId, c.senderId))) {
    lastError = `The sender ID “${c.senderId}” is no longer approved, so this scheduled send was not sent.`
    stopped = true
  }

  while (!stopped && progress < total) {
    if (opts.deadline && Date.now() > opts.deadline) break
    const batch = c.recipients.slice(progress, progress + BATCH_SIZE)
    let accepted = false
    try {
      const result = await sendSmsBatch({
        senderId: c.senderId,
        messages: batch.map((recipient, j) => ({ recipient, message: c.message, ref: messageRef(c.id, progress + j) })),
      })
      if (result.ok) accepted = true
      else {
        lastError = result.reason
        // A sender ID or auth failure will repeat for every batch.
        if (result.code === 'ASMS07' || result.code.startsWith('AIN')) stopped = true
      }
    } catch (error) {
      lastError = error instanceof Error ? error.message : 'The SMS service is unavailable.'
    }
    const from = progress
    progress += batch.length
    if (accepted) sent += batch.length
    await db
      .update(campaigns)
      .set({
        sendProgress: progress,
        sentCount: sent,
        providerResponse: lastError,
        lockedUntil: new Date(Date.now() + LEASE_MS),
        ...(accepted ? {} : { delivery: sql`coalesce(${campaigns.delivery}, '{}'::jsonb) || ${JSON.stringify(notSentPatch(from, progress))}::jsonb` }),
      })
      .where(eq(campaigns.id, c.id))
  }

  // Stopped early: nothing after this point will be sent.
  if (stopped && progress < total) {
    await db
      .update(campaigns)
      .set({ delivery: sql`coalesce(${campaigns.delivery}, '{}'::jsonb) || ${JSON.stringify(notSentPatch(progress, total))}::jsonb` })
      .where(eq(campaigns.id, c.id))
    progress = total
  }

  if (progress < total) {
    // Out of time: end the lease now (not clear it, since only sends with a
    // lease are ever resumed) so the next run carries on straight away.
    await db.update(campaigns).set({ status: 'sending', lockedUntil: new Date(Date.now() - 1) }).where(eq(campaigns.id, c.id))
    return { id: c.id, done: false, status: 'sending', delivered: sent, total, segments: c.segments, creditsUsed: c.creditsUsed, error: lastError }
  }

  const reserved = total * c.segments
  const refunded = (total - sent) * c.segments
  await refundCredits(c.userId, refunded)
  const status = sent === 0 ? 'failed' : sent < total ? 'partial' : 'sent'
  await db
    .update(campaigns)
    .set({ status, sendProgress: total, sentCount: sent, creditsUsed: reserved - refunded, providerResponse: lastError, lockedUntil: null })
    .where(eq(campaigns.id, c.id))
  if (sent > 0) {
    await db.update(accounts).set({ defaultSenderId: c.senderId }).where(eq(accounts.userId, c.userId))
  }
  return { id: c.id, done: true, status, delivered: sent, total, segments: c.segments, creditsUsed: reserved - refunded, error: lastError }
}

// Deducts credits up front, sends in batches of 100 and refunds any batch
// Moolre rejects.
export async function sendCampaign(input: SendInput) {
  const { id } = await createCampaign({ ...input, scheduledFor: null })
  const result = await dispatchCampaign(id)
  return {
    id: result.id,
    status: result.status as 'sent' | 'partial' | 'failed',
    delivered: result.delivered,
    total: result.total,
    segments: result.segments,
    creditsUsed: result.creditsUsed,
    error: result.error,
  }
}

// Books a send for later. Credits are reserved now and refunded for anything
// that ends up unsent, or in full if the send is cancelled first.
export async function scheduleCampaign(input: SendInput & { scheduledFor: Date }) {
  const lead = input.scheduledFor.getTime() - Date.now()
  if (!Number.isFinite(lead) || lead < MIN_SCHEDULE_LEAD_MS) {
    throw new SendError('schedule_at must be at least 2 minutes in the future.', 'invalid_schedule', 422)
  }
  if (lead > MAX_SCHEDULE_AHEAD_MS) throw new SendError('schedule_at can be at most 60 days ahead.', 'invalid_schedule', 422)
  const { id, cost, segments } = await createCampaign(input)
  return { id, status: 'scheduled' as const, scheduledFor: input.scheduledFor, total: input.recipients.length, segments, creditsUsed: cost }
}

// Cancels a scheduled send that hasn't started and returns its credits.
export async function cancelScheduledCampaign(userId: string, campaignId: number) {
  const [row] = await db
    .update(campaigns)
    .set({ status: 'cancelled', providerResponse: 'Cancelled before sending.' })
    .where(and(eq(campaigns.id, campaignId), eq(campaigns.userId, userId), eq(campaigns.status, 'scheduled')))
    .returning({ id: campaigns.id, creditsUsed: campaigns.creditsUsed })
  if (!row) {
    const [existing] = await db
      .select({ status: campaigns.status })
      .from(campaigns)
      .where(and(eq(campaigns.id, campaignId), eq(campaigns.userId, userId)))
    if (!existing) throw new SendError('No message with that id.', 'not_found', 404)
    throw new SendError(`This send is ${existing.status}, so it can no longer be cancelled.`, 'not_cancellable', 409)
  }
  await refundCredits(userId, row.creditsUsed)
  await db.update(campaigns).set({ creditsUsed: 0 }).where(eq(campaigns.id, row.id))
  return { id: row.id, creditsRefunded: row.creditsUsed }
}

// Takes the lease on a send if nobody else holds it. Returns false if another
// run got there first.
async function claim(campaignId: number, from: 'scheduled' | 'sending') {
  const now = new Date()
  const lease = new Date(now.getTime() + LEASE_MS)
  const [row] = await db
    .update(campaigns)
    .set({ status: 'sending', lockedUntil: lease })
    .where(
      from === 'scheduled'
        ? and(eq(campaigns.id, campaignId), eq(campaigns.status, 'scheduled'))
        : and(eq(campaigns.id, campaignId), eq(campaigns.status, 'sending'), isNotNull(campaigns.lockedUntil), lt(campaigns.lockedUntil, now)),
    )
    .returning({ id: campaigns.id })
  return Boolean(row)
}

// Run by the every-minute job: sends scheduled sends that are due and resumes
// any send whose sender stopped mid-way (its lease expired), including one that
// sent every batch but stopped before refunding and recording the result. Only SMS sends
// that recorded a lease are ever resumed, so sends from before resumable
// sending existed are never touched.
export async function runDueCampaigns(opts: { budgetMs: number }) {
  const deadline = Date.now() + opts.budgetMs
  const now = new Date()
  const due = await db
    .select({ id: campaigns.id })
    .from(campaigns)
    .where(and(eq(campaigns.status, 'scheduled'), eq(campaigns.channel, 'sms'), lte(campaigns.scheduledFor, now)))
    .orderBy(asc(campaigns.scheduledFor))
    .limit(20)
  const stalled = await db
    .select({ id: campaigns.id })
    .from(campaigns)
    .where(
      and(
        eq(campaigns.status, 'sending'),
        eq(campaigns.channel, 'sms'),
        isNotNull(campaigns.lockedUntil),
        lt(campaigns.lockedUntil, now),
        sql`${campaigns.createdAt} > ${new Date(now.getTime() - RESUME_MAX_AGE_MS)}`,
      ),
    )
    .orderBy(asc(campaigns.createdAt))
    .limit(20)

  const results: DispatchResult[] = []
  const work: [number, 'scheduled' | 'sending'][] = [
    ...stalled.map((r) => [r.id, 'sending'] as [number, 'sending']),
    ...due.map((r) => [r.id, 'scheduled'] as [number, 'scheduled']),
  ]
  for (const [id, from] of work) {
    if (Date.now() > deadline) break
    if (!(await claim(id, from))) continue
    try {
      results.push(await dispatchCampaign(id, { deadline }))
    } catch (error) {
      console.error('Scheduled send failed', id, error)
      // Let the lease lapse so a later run retries.
    }
  }
  return results
}
