import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { admin, apiKey, jwt, username } from "better-auth/plugins";
import type { User } from "better-auth/types";
import { eq } from "drizzle-orm";
import { db } from "../db/db.js";
import * as rawSchema from "../db/schema/auth-schema.js";
import { sendEmail } from "../utils/mail/sendMail.js";

export const schema = {
	user: rawSchema.user,
	session: rawSchema.session,
	account: rawSchema.account,
	verification: rawSchema.verification,
	jwks: rawSchema.jwks,
	apiKey: rawSchema.apikey, // 🔑 rename to apiKey
};
const RESET_EXPIRY_SECONDS = 3600; // 1 hour

export const auth = betterAuth({
	database: drizzleAdapter(db, {
		provider: "pg",
		schema,
	}),
	trustedOrigins: [
		"*.alpla.net",
		"http://localhost:5173",
		"http://localhost:5500",
		"http://localhost:4200",
		"http://localhost:4000",
	],
	appName: "lst",
	emailAndPassword: {
		enabled: true,
		minPasswordLength: 8, // optional config
		resetPasswordTokenExpirySeconds: RESET_EXPIRY_SECONDS, // time in seconds
		sendResetPassword: async ({ user, token }) => {
			const frontendUrl = `${process.env.BETTER_AUTH_URL}/lst/app/user/resetpassword?token=${token}`;
			const expiryMinutes = Math.floor(RESET_EXPIRY_SECONDS / 60);
			const expiryText =
				expiryMinutes >= 60
					? `${expiryMinutes / 60} hour${expiryMinutes === 60 ? "" : "s"}`
					: `${expiryMinutes} minutes`;
			const emailData = {
				email: user.email,
				subject: "LST- Forgot password request",
				template: "forgotPassword",
				context: {
					username: user.name,
					email: user.email,
					url: frontendUrl,
					expiry: expiryText,
				},
			};
			await sendEmail(emailData);
		},
		// onPasswordReset: async ({ user }, request) => {
		//     // your logic here
		//     console.log(`Password for user ${user.email} has been reset.`);
		// },
	},
	plugins: [
		//jwt({ jwt: { expirationTime: "1h" } }),
		apiKey(),
		admin(),
		username(),
	],
	session: {
		expiresIn: 60 * 60,
		updateAge: 60 * 5,
		freshAge: 60 * 2,
		cookieCache: {
			enabled: true,
			maxAge: 5 * 60,
		},
	},
	cookie: {
		path: "/lst/app",
		sameSite: "lax",
		secure: false,
		httpOnly: true,
	},
	events: {
		async onSignInSuccess({ user }: { user: User }) {
			await db
				.update(schema.user)
				.set({ lastLogin: new Date() })
				.where(eq(schema.user.id, user.id));
		},
	},
});

export type Auth = typeof auth;
