const accountSid = process.env.TWILIO_ACCOUNT_SID
const authToken = process.env.TWILIO_AUTH_TOKEN

type AccountStatus = "active" | "suspended" | "closed"

interface TwilioAccountInfo {
  status: AccountStatus
  balance?: string
  currency?: string
}

export async function getTwilioAccountInfo(): Promise<TwilioAccountInfo | undefined> {
  if (!accountSid || !authToken) {
    return undefined
  }

  const credentials = Buffer.from(`${accountSid}:${authToken}`).toString("base64")
  const headers = { Authorization: `Basic ${credentials}` }

  const [accountRes, balanceRes] = await Promise.all([
    fetch(`https://api.twilio.com/2010-04-01/Accounts/${accountSid}.json`, { headers }),
    fetch(`https://api.twilio.com/2010-04-01/Accounts/${accountSid}/Balance.json`, { headers }),
  ])

  if (!accountRes.ok) {
    return undefined
  }

  const account = (await accountRes.json()) as { status: AccountStatus }
  const info: TwilioAccountInfo = { status: account.status }

  if (balanceRes.ok) {
    const balance = (await balanceRes.json()) as { balance: string; currency: string }
    info.balance = balance.balance
    info.currency = balance.currency
  }

  return info
}

export function formatTwilioError(info: TwilioAccountInfo): string {
  if (info.status === "suspended") {
    const balanceInfo = info.balance ? ` (balance: ${info.balance} ${info.currency})` : ""
    return `Twilio account suspended${balanceInfo} - add funds at twilio.com/console`
  }
  if (info.status === "closed") {
    return "Twilio account is closed"
  }
  return `Twilio account status: ${info.status}`
}
