import type { LogLine } from '@types'
import { get, handleError, makeUrl } from '../http'
import { resolveAppName } from '../name'

export const printLog = (line: LogLine) =>
  console.log(`${new Date(line.time).toLocaleTimeString()} ${line.text}`)

export async function logApp(arg: string | undefined, options: { follow?: boolean }) {
  const name = resolveAppName(arg)
  if (!name) return

  if (options.follow) {
    await tailLogs(name)
    return
  }

  const logs: LogLine[] | undefined = await get(`/api/apps/${name}/logs`)
  if (!logs) {
    console.error(`App not found: ${name}`)
    return
  }
  if (logs.length === 0) {
    console.log('No logs yet')
    return
  }
  for (const line of logs) {
    printLog(line)
  }
}

export async function tailLogs(name: string) {
  try {
    const url = makeUrl(`/api/apps/${name}/logs/stream`)
    const res = await fetch(url)
    if (!res.ok) {
      console.error(`App not found: ${name}`)
      return
    }
    if (!res.body) return

    const reader = res.body.getReader()
    const decoder = new TextDecoder()
    let buffer = ''

    while (true) {
      const { done, value } = await reader.read()
      if (done) break

      buffer += decoder.decode(value, { stream: true })
      const lines = buffer.split('\n\n')
      buffer = lines.pop() ?? ''

      for (const line of lines) {
        if (line.startsWith('data: ')) {
          const data = JSON.parse(line.slice(6)) as LogLine
          printLog(data)
        }
      }
    }
  } catch (error) {
    handleError(error)
  }
}
