import { betterAuth } from 'better-auth'
import { pikkuBetterAuth } from '#pikku'

/**
 * Better Auth configuration — email + password sign-in.
 *
 * `pikkuBetterAuth` has no side effects: the pikku CLI statically inspects this
 * single exported `auth` const and generates the catch-all `/api/auth/**` HTTP
 * wiring, the session-bridge middleware, and a `wireSecret` for
 * `BETTER_AUTH_SECRET` (and one per social provider, if you add any) — so the
 * auth routes and secret requirements flow through normal inspection into the
 * deploy manifest.
 *
 * The factory runs once when singleton services are built, pulling the secret
 * (and the database) off the injected `services`; the resolved instance is then
 * available to every function as `services.auth`. Better Auth is given the app's
 * own kysely: the CamelCasePlugin maps Better Auth's camelCase field names onto
 * the snake_case columns. The schema itself is not hand-written — run
 * `pikku db generate` to emit the migration from this config (see
 * db/sqlite/*-better-auth.sql). To offer Google / GitHub / ... add a
 * `socialProviders` entry (and a button on the login page) — the CLI wires its
 * secret too.
 */
export const auth = pikkuBetterAuth(async ({ kysely, secrets }) => {
  const BETTER_AUTH_SECRET = await secrets.getSecret('BETTER_AUTH_SECRET')

  return betterAuth({
    secret: BETTER_AUTH_SECRET,
    database: { db: kysely, type: 'sqlite' },
    emailAndPassword: { enabled: true },
    // Stateless session: CLI splits out betterAuthStatelessSession so non-auth
    // units verify the signed cookie instead of bundling better-auth. pikku #737.
    session: { cookieCache: { enabled: true } },
    advanced: { database: { generateId: 'uuid' } },
  })
})
