import "server-only";

/**
 * Neon Auth (Better Auth) — server-side configuration.
 *
 * This file is Node-only. It is imported by:
 *   - `src/app/api/auth/[...nextauth]/route.ts` (the API handler)
 *   - Server actions that call signIn / signOut
 *   - `src/lib/admin-permissions.ts` (reads getSession() for the current user)
 *
 * The middleware imports a separate, edge-safe instance built from
 * `src/auth.config.ts`. Both instances share the same session cookie,
 * so the middleware can read sessions minted here.
 *
 * Auth providers: configured in the Neon Auth dashboard (oauth-provider).
 * Neon Auth manages its own users in the `neon_auth.user` table.
 * Our `admin_users` table links to Neon Auth users by email.
 */

import { createNeonAuth } from "@neondatabase/auth/next/server";
import { getNeonAuthConfig } from "@/auth.config";

const auth = createNeonAuth({
  baseUrl: getNeonAuthConfig().baseUrl,
  cookies: { secret: getNeonAuthConfig().cookieSecret },
});

export const { getSession, signIn, signOut, resetPassword, requestPasswordReset } = auth;
export const { listUsers, createUser, setRole, setUserPassword, updateUser } = auth.admin;

/**
 * Re-exported for the API route handler compatibility.
 * `GET` and `POST` from `auth.handler()` handle all Neon Auth endpoints.
 */
const authInstance = auth.handler();
export const { GET: handlersGET, POST: handlersPOST } = authInstance;

/**
 * Re-exported for middleware compatibility (edge runtime can't use Node-only auth).
 * The middleware uses `neonAuthMiddleware` from `@neondatabase/auth/next/server` directly.
 * This named export exists for call sites that import `auth` from this module.
 */
export { auth };
