import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { db, schema } from "@pkg/db";
import { env as publicEnv } from "$env/dynamic/public";
import { getRedisInstance } from "../../../server/redis";
import { admin, username, openAPI } from "better-auth/plugins";
import { UserRoleMap } from "../../../core/enums";
import { hashPassword, verifyPassword } from "../domain/hash";
import { env } from "$env/dynamic/private";

export const auth = betterAuth({
	trustedOrigins: ["http://localhost:5173", env.BETTER_AUTH_URL],
	advanced: { useSecureCookies: publicEnv.PUBLIC_NODE_ENV === "production" },
	emailAndPassword: {
		enabled: true,
		password: { hash: hashPassword, verify: verifyPassword },
	},
	plugins: [
		openAPI(),
		username(),
		admin({
			defaultRole: UserRoleMap.ADMIN,
			defaultBanReason:
				"Stop fanum taxing the server bub, losing aura points fr",
			defaultBanExpiresIn: 60 * 60 * 24,
		}),
	],
	logger: {
		level: publicEnv.PUBLIC_NODE_ENV === "production" ? "error" : "debug",
	},
	database: drizzleAdapter(db, { provider: "pg", schema: { ...schema } }),
	secondaryStorage: {
		get: async (key) => {
			const redis = getRedisInstance();
			return await redis.get(key);
		},
		set: async (key, value, ttl) => {
			const redis = getRedisInstance();
			if (ttl) {
				await redis.setex(key, ttl, value);
			} else {
				await redis.set(key, value);
			}
		},
		delete: async (key) => {
			const redis = getRedisInstance();
			const out = await redis.del(key);
			if (!out && out !== 0) {
				return null;
			}
			return out.toString() as any;
		},
	},
	session: {
		modelName: "session",
		expiresIn: 60 * 60 * 24 * 7,
		updateAge: 60 * 60 * 24,
	},
	user: {
		changeEmail: { enabled: true },
		modelName: "user",
		additionalFields: {
			parentId: { required: false, type: "string" },
			discountPercent: {
				required: false,
				type: "number",
				defaultValue: 0,
				fieldName: "discount_percent",
			},
		},
	},
});
