// Server-only phone sign-in for the AkotoCreative SMS Android app. A customer
// enters the number saved on their account (Settings → Text alerts), gets a
// 6-digit code by SMS from the platform sender ID, and the app receives an API
// key named "Phone app" that the customer can see and revoke under
// Dashboard → API keys.
//
// Requests get the same answer whether or not the number belongs to an
// account, so the form can't be used to find out who is a customer.
import { and, asc, desc, eq, gt, isNotNull, isNull, sql } from 'drizzle-orm'
import { db } from '../../db/index.js'
import { accounts, apiKeys, autoMessages, loginCodes } from '../../db/schema.js'
import { generateApiKey } from './api-keys.server'
import { SendError } from './messaging.server'
import { getMoolreConfig, sendSmsBatch } from './moolre.server'
import { describeDevice, notify } from './notifications.server'
import { normalizeGhanaPhone } from './sms'

export const CODE_TTL_MS = 10 * 60_000
const MAX_ATTEMPTS = 5
const MAX_CODES_PER_PHONE = 3 // per 15 minutes
const MAX_CODES_PER_IP = 10 // per hour
const MAX_ACTIVE_KEYS = 10
export const APP_KEY_NAME = 'Phone app'

async function sha256(value: string) {
  const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value))
  return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('')
}

const hashCode = (phone: string, code: string) => sha256(`login:${phone}:${code}`)

function sixDigits() {
  const n = crypto.getRandomValues(new Uint32Array(1))[0] % 1_000_000
  return String(n).padStart(6, '0')
}

function sameText(a: string, b: string) {
  if (a.length !== b.length) return false
  let diff = 0
  for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i)
  return diff === 0
}

export function readPhone(raw: string) {
  const phone = normalizeGhanaPhone(raw)
  if (!phone) throw new SendError('Enter a Ghana mobile number, like 024 123 4567.', 'invalid_phone', 422)
  return phone
}

// Texts a code if exactly one account has this number saved.
export async function requestLoginCode(rawPhone: string, ip: string | null) {
  const phone = readPhone(rawPhone)
  const now = Date.now()

  const [perPhone] = await db
    .select({ n: sql<number>`count(*)::int` })
    .from(loginCodes)
    .where(and(eq(loginCodes.phone, phone), gt(loginCodes.createdAt, new Date(now - 15 * 60_000))))
  if (perPhone.n >= MAX_CODES_PER_PHONE) {
    throw new SendError('Too many codes were asked for this number. Wait 15 minutes and try again.', 'too_many_requests', 429)
  }
  if (ip) {
    const [perIp] = await db
      .select({ n: sql<number>`count(*)::int` })
      .from(loginCodes)
      .where(and(eq(loginCodes.ip, ip), gt(loginCodes.createdAt, new Date(now - 60 * 60_000))))
    if (perIp.n >= MAX_CODES_PER_IP) {
      throw new SendError('Too many sign-in codes were asked for from this network. Try again in an hour.', 'too_many_requests', 429)
    }
  }

  const owners = await db.select({ userId: accounts.userId }).from(accounts).where(eq(accounts.phone, phone)).limit(2)
  const expiresAt = new Date(now + CODE_TTL_MS)
  if (owners.length !== 1) {
    // No single account uses this number: record the request (for the limits
    // above) and answer exactly as if a code was sent.
    await db.insert(loginCodes).values({ phone, ip, expiresAt })
    return { expiresInSeconds: CODE_TTL_MS / 1000 }
  }

  const { senderId } = await getMoolreConfig()
  if (!senderId) {
    throw new SendError('Sign-in by text message is not available right now. Sign in with an API key instead.', 'sms_unavailable', 503)
  }
  const code = sixDigits()
  const userId = owners[0].userId
  await db.insert(loginCodes).values({ phone, userId, codeHash: await hashCode(phone, code), ip, expiresAt })

  const message = `Your AkotoCreative SMS sign-in code is ${code}. It expires in 10 minutes. Never share it with anyone.`
  let error: string | null = null
  try {
    const result = await sendSmsBatch({ senderId, messages: [{ recipient: phone, message, ref: `L${Date.now()}` }] })
    if (!result.ok) error = result.reason
  } catch (err) {
    error = err instanceof Error ? err.message : 'The SMS service is unavailable.'
  }
  try {
    // Logged like other automatic texts, with the code hidden.
    await db.insert(autoMessages).values({
      userId,
      event: 'login_code',
      phone,
      message: message.replace(code, '••••••'),
      status: error ? 'failed' : 'sent',
      error,
    })
  } catch (err) {
    console.error('Could not log sign-in code text', err)
  }
  if (error) throw new SendError('We could not text your code just now. Try again in a minute.', 'sms_unavailable', 503)
  return { expiresInSeconds: CODE_TTL_MS / 1000 }
}

// Checks a code and, if right, issues an API key for the app.
export async function verifyLoginCode(rawPhone: string, rawCode: string, userAgent: string | null) {
  const phone = readPhone(rawPhone)
  const code = rawCode.replace(/\D/g, '')
  const wrong = new SendError('That code is wrong or has expired. Check the text, or ask for a new code.', 'invalid_code', 401)
  if (code.length !== 6) throw wrong

  const [row] = await db
    .select()
    .from(loginCodes)
    .where(and(eq(loginCodes.phone, phone), isNotNull(loginCodes.userId), isNull(loginCodes.usedAt), gt(loginCodes.expiresAt, new Date())))
    .orderBy(desc(loginCodes.createdAt))
    .limit(1)
  if (!row || !row.codeHash || !row.userId) throw wrong
  if (row.attempts >= MAX_ATTEMPTS) throw wrong

  if (!sameText(row.codeHash, await hashCode(phone, code))) {
    await db
      .update(loginCodes)
      .set({ attempts: sql`${loginCodes.attempts} + 1` })
      .where(eq(loginCodes.id, row.id))
    throw wrong
  }
  // Claim the code once, even if two requests race.
  const [claimed] = await db
    .update(loginCodes)
    .set({ usedAt: new Date() })
    .where(and(eq(loginCodes.id, row.id), isNull(loginCodes.usedAt)))
    .returning({ id: loginCodes.id })
  if (!claimed) throw wrong

  const userId = row.userId
  // Keep within the key limit by retiring the oldest phone-app key if needed.
  const active = await db
    .select({ id: apiKeys.id, name: apiKeys.name })
    .from(apiKeys)
    .where(and(eq(apiKeys.userId, userId), isNull(apiKeys.revokedAt)))
    .orderBy(asc(apiKeys.createdAt))
  if (active.length >= MAX_ACTIVE_KEYS) {
    const oldestApp = active.find((k) => k.name.startsWith(APP_KEY_NAME))
    if (!oldestApp) {
      throw new SendError(
        `Your account already has ${MAX_ACTIVE_KEYS} API keys. Revoke one under Dashboard → API keys, then try again.`,
        'too_many_keys',
        409,
      )
    }
    await db.update(apiKeys).set({ revokedAt: new Date() }).where(eq(apiKeys.id, oldestApp.id))
  }

  const device = describeDevice(userAgent)
  const name = `${APP_KEY_NAME} (${device})`.slice(0, 60)
  const { key, prefix, keyHash } = await generateApiKey()
  await db.insert(apiKeys).values({ userId, name, prefix, keyHash })

  const [account] = await db
    .select({ email: accounts.email, name: accounts.name })
    .from(accounts)
    .where(eq(accounts.userId, userId))
  await notify(userId, {
    type: 'security',
    title: 'Signed in on the phone app',
    body: `Your account was signed in on the AkotoCreative SMS app with a code sent to your number. If this wasn’t you, revoke the “${APP_KEY_NAME}” key under Dashboard → API keys.`,
  })
  return { key, keyName: name, email: account?.email ?? '', name: account?.name ?? null }
}
