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

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

export const auth = betterAuth({
    database: drizzleAdapter(db, {
        provider: "pg",
        schema,
    }),
    appName: "lst",
    emailAndPassword: {
        enabled: true,
        minPasswordLength: 8, // optional config
    },
    plugins: [
        jwt({ jwt: { expirationTime: "1h" } }),
        apiKey(),
        admin(),
        username(),
    ],
    session: {
        expiresIn: 60 * 60,
        updateAge: 60 * 1,
        cookieCache: {
            enabled: true,
            maxAge: 5 * 60, // Cache duration in seconds
        },
    },
    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;
