import { DrizzlePostgreSQLAdapter } from "@lucia-auth/adapter-drizzle";
import { Discord } from "arctic";
import { Lucia } from "lucia";
import db from "~/drizzle";
import { sessions, users } from "~/drizzle/schema";

if (typeof import.meta.env.PROD === "undefined")
  throw new Error("No env PROD found!");

if (typeof import.meta.env.VITE_DISCORD_CLIENT_ID === "undefined")
  throw new Error("No env VITE_DISCORD_CLIENT_ID found!");

if (typeof import.meta.env.VITE_DISCORD_CLIENT_SECRET === "undefined")
  throw new Error("No env PROD found!");

if (typeof import.meta.env.VITE_AUTH_REDIRECT_URL === "undefined")
  throw new Error("No env VITE_AUTH_REDIRECT_URL found!");

const adapter = new DrizzlePostgreSQLAdapter(db, sessions, users);

export const lucia = new Lucia(adapter, {
  sessionCookie: {
    attributes: {
      // set to `true` when using HTTPS
      secure: import.meta.env.PROD,
    },
  },
  getUserAttributes: (attributes) => attributes,
});

export const discord = new Discord(
  import.meta.env.VITE_DISCORD_CLIENT_ID,
  import.meta.env.VITE_DISCORD_CLIENT_SECRET,
  import.meta.env.VITE_AUTH_REDIRECT_URL,
);

const unencoded = `${import.meta.env.VITE_DISCORD_CLIENT_ID}:${import.meta.env.VITE_DISCORD_CLIENT_SECRET}`;
const encoded = btoa(unencoded);

export const BasicAuth = {
  unencoded: `Basic ${unencoded}`,
  encoded: `Basic ${encoded}`,
};
