export const requireAuth = (handler: (req: Request) => Response | Promise<Response>) => {
  return async (req: Request) => {
    if (process.env.NODE_ENV !== "production") {
      return handler(req)
    }

    const cookies = new Bun.CookieMap(req.headers.get("cookie") ?? "")
    if (cookies.get("auth") === "authenticated") {
      return handler(req)
    }

    if (validAuth(req)) {
      const response = await handler(req)
      const newHeaders = new Headers(response.headers)

      const url = new URL(req.url)
      const cookieDomain = `.${url.hostname.split(".").slice(-2).join(".")}`

      const oneYearInSeconds = 60 * 60 * 24 * 365
      const authCookie = new Bun.Cookie({
        name: "auth",
        value: "authenticated",
        domain: cookieDomain,
        path: "/",
        maxAge: oneYearInSeconds,
        httpOnly: true,
      })

      newHeaders.set("Set-Cookie", authCookie.toString())

      return new Response(response.body, { status: response.status, headers: newHeaders })
    }

    return new Response("Unauthorized", {
      status: 401,
      headers: { "WWW-Authenticate": 'Basic realm="Workshop Access"' },
    })
  }
}

const validAuth = (req: Request): boolean => {
  const logins = ["spike:888", "defunkt:888", "probablycorey:888"]
  const auth = req.headers.get("authorization")
  return logins.some((login) => `Basic ${btoa(login)}` === auth)
}
