/**
 * Build time environment variables are not available in Netlify functions at
 * runtime. The official workaround is to create an artifact and include that
 * in the bundled functions so that the function can load/read it at runtime.
 * In other words, during the build fill the .env file with the environment
 * variables needed and then instruct Netlify to include the .env file together
 * with the bundled function.
 *
 * This works but has two things to consider:
 *
 * 1. Any environment variable created in the Netlify UI will be considered
 *    defined. Even if the variable is set to "empty" in the Netlify UI it is
 *    still an empty string and therefore defined.
 *
 * 2. Next.js uses @next/env to automatically read the .env
 *    file into the process environment. @next/env does NOT override any
 *    defined variables, empty strings are also considered defined. So for
 *    @next/env to automatically pick up the .env file in the bundled functions
 *    we need to make sure that none of the variables in the .env file are
 *    defined in the Netlify UI. @next/env does not have any "override=true"
 *    option, like dotenv package. So rather than introduce dotenv and manually
 *    use it in *every* function, we can delegate to @next/env if we keep the
 *    environment variables in Netlify UI in check.
 *
 * We only run this on Netlify build.
 *
 * We define PUBLIC_URL and use that because we are behind Akamai reverse proxy.
 * For the stable environments (test, stage, production) these are defined. For
 * any other environment (branch deploys and deploy previews) we use the
 * predefined Netlify environment variable DEPLOY_PRIME_URL.
 *
 * Both AUTH_URL and NEXTAUTH_URL is set to point to the PUBLIC_URL.
 * We set both as a precaution as next-auth v5 is transitioning to AUTH_* but we
 * have seen several occurences in the auth.js codebase that are not using both.
 */

import fs from "node:fs"

if (process.env.NETLIFY) {
  const PUBLIC_URLS = {
    production: "https://www.scandichotels.com",
    stage: "https://stage.scandichotels.com",
    test: "https://test2.scandichotels.com",
  }

  let PUBLIC_URL
  if (PUBLIC_URLS[process.env.CONTEXT]) {
    PUBLIC_URL = PUBLIC_URLS[process.env.CONTEXT]
  } else if (PUBLIC_URLS[process.env.BRANCH]) {
    PUBLIC_URL = PUBLIC_URLS[process.env.BRANCH]
  } else {
    PUBLIC_URL = process.env.DEPLOY_PRIME_URL
  }

  const AUTH_URL = `${PUBLIC_URL}/api/web/auth`
  const NEXTAUTH_URL = AUTH_URL

  const replaceMap = {
    AUTH_URL,
    NEXTAUTH_URL,
    PUBLIC_URL,
  }

  let contents = fs.readFileSync("./.env", { encoding: "utf-8" })

  for (const [key, value] of Object.entries(replaceMap)) {
    contents = contents.replace(new RegExp(`${key}=.*`), `${key}="${value}"`)
  }

  fs.writeFileSync("./.env", contents, { encoding: "utf-8" })
}
