import colors, { Color } from "colors"
import fs from "fs"
import { NextApiRequest } from "next"

colors.enable()

const loggingTemplates: {
  system: LoggingType
  infoGreen: LoggingType
  infoCyan: LoggingType
  debug: LoggingType
  post: LoggingType
  warn: LoggingType
  error: LoggingType
} = {
  system: ["SYSTEM", "green"],
  infoGreen: ["INFO", "green"],
  infoCyan: ["INFO", "cyan"],
  debug: ["Debug", "grey"],
  post: ["Post", "white"],
  warn: ["WARN", "yellow"],
  error: ["ERROR", "red"],
}

type LoggingType = [string, keyof Color]
export type Logging = keyof typeof loggingTemplates | LoggingType

let started: boolean = false

async function logStartup() {
  await fs.promises.stat("log").catch(async () => {
    await fs.promises.mkdir("log")
    await logging(`Created 'log' Folder.`, ["infoCyan", "system"])
  })
  started = true
}

async function logging(
  message: string,
  types: Logging[],
  req?: NextApiRequest
) {
  if (!started) await logStartup()
  const messages = { console: message, file: message }
  types
    .slice()
    .reverse()
    .forEach(async (type) => {
      const [name, color] =
        typeof type === "object" ? type : loggingTemplates[type]
      messages.console = `[${name}] `[color] + messages.console
      messages.file = `[${name}] ` + messages.file
    })
  messages.console =
    `[${new Date().toString().slice(0, 33)}] ` + messages.console
  messages.file = `[${new Date().toString().slice(0, 33)}] ` + messages.file
  if (req) {
    const forwardedFor: any = req.headers["x-forwarded-for"]
    const ip = (forwardedFor || "127.0.0.1, 192.168.178.1").split(",")
    const route = req.url
    messages.console = [ip[0].yellow, route?.green, messages.console].join(
      " - "
    )
    messages.file = [ip[0], route, messages.file].join(" - ")
  }
  await fs.promises.appendFile("log/log.txt", messages.file + "\n")
  console.log(messages.console)
}

export default logging
