import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { admin, username } from "better-auth/plugins";
import { reactStartCookies } from "better-auth/react-start";
import { database } from "../db";
import * as schema from "../db/schema/auth";
import {
	accessControl,
	adminRole,
	moderatorRole,
	userRole,
} from "./auth/permissions";

const auth = betterAuth({
	database: drizzleAdapter(database, {
		provider: "sqlite",
		schema: schema,
	}),
	trustedOrigins: [process.env.CORS_ORIGIN || ""],
	emailAndPassword: {
		enabled: true,
	},
	advanced: {
		defaultCookieAttributes: {
			sameSite: "none",
			secure: true,
			httpOnly: true,
		},
	},
	plugins: [
		admin({
			ac: accessControl,
			roles: {
				admin: adminRole,
				moderator: moderatorRole,
				user: userRole,
			},
			defaultRole: "user",
		}),
		username(),
		reactStartCookies(),
	],
});

export default auth;
export { auth };
