import { betterAuth } from "better-auth";
import Database from "better-sqlite3";
import { jwt } from "better-auth/plugins";
import { oidcProvider } from "better-auth/plugins";

export const auth = betterAuth({
  database: new Database("./auth.db"),
  baseURL: process.env.BETTER_AUTH_URL ?? "http://localhost:4000",
  emailAndPassword: {
    enabled: true,
  },
  session: {
    cookieCache: {
      enabled: true,
      maxAge: 60 * 5, // 5 minutes
    },
  },
  plugins: [
    jwt({
      // SpacetimeDB will verify JWTs via JWKS
      jwks: true,
      // Include standard OIDC claims that SpacetimeDB expects
      definePayload: async ({ session, user }) => ({
        sub: user.id,
        email: user.email,
        name: user.name,
      }),
    }),
    oidcProvider({
      loginPage: "/sign-in",
      metadata: {
        issuer: process.env.BETTER_AUTH_URL ?? "http://localhost:4000",
      },
    }),
  ],
});

export type Auth = typeof auth;
