import { ensure } from "@workshop/shared/utils"
import { bold, time } from "discord.js"

export const getLogs = async (type: "app" | "request" | "build" = "app", limit = 20) => {
  const ownerId = "tea-d1vamb95pdvs73d1sgtg" // owner ID for the Render project (from the render api)
  const resourceId = "srv-d1vrdqmuk2gs73eop8o0" // resource ID for the Render service (from the render api)

  const url = new URL("https://api.render.com/v1/logs")
  url.searchParams.set("type", type)
  url.searchParams.set("ownerId", ownerId)
  url.searchParams.set("direction", "backward")
  url.searchParams.set("resource", resourceId)
  url.searchParams.set("limit", String(limit))

  const response = await fetch(url.toString(), {
    method: "GET",
    headers: {
      accept: "application/json",
      authorization: `Bearer ${process.env.RENDER_API_KEY}`,
    },
  })
  if (!response.ok) {
    throw new Error(`Failed to fetch logs: ${response.statusText}`)
  }

  const data = (await response.json()) as any
  ensure(data.logs, "Expected logs to be an array")
  const logs = data.logs.map((log: any) => {
    const { timestamp, message } = log

    const unixTimestamp = Math.floor(new Date(timestamp).getTime() / 1000)
    const cleanMessage = message.replace(/\x1b\[[0-9;]*m/g, "")
    return `${time(unixTimestamp, "t")}: ${cleanMessage}`
  })

  return logs
}
