// Better-auth server config
// Docs: https://better-auth.com
import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
import { prisma } from "@/lib/db";

export const auth = betterAuth({
  baseURL:
    process.env.BETTER_AUTH_URL ?? process.env.NEXT_PUBLIC_SITE_URL ?? "http://localhost:3000",
  secret: process.env.BETTER_AUTH_SECRET ?? process.env.NEXTAUTH_SECRET,

  database: prismaAdapter(prisma, {
    provider: "postgresql",
    debugLogs: process.env.NODE_ENV === "development",
  }),

  // Better-auth defaults to PascalCase model names but our schema uses
  // lowercase (@@map). Override resolution:
  // - User → user, Session → session, Account → account, Verification → verification

  // Email + password (instant access; magic link layered later)
  emailAndPassword: {
    enabled: true,
    autoSignIn: true,
    minPasswordLength: 8,
    maxPasswordLength: 128,
    requireEmailVerification: false, // toggle on once email provider configured
  },

  // OAuth — Google (TODO: enable when client id/secret provided)
  socialProviders: {
    google:
      process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET
        ? {
            clientId: process.env.GOOGLE_CLIENT_ID,
            clientSecret: process.env.GOOGLE_CLIENT_SECRET,
          }
        : undefined,
  },

  session: {
    expiresIn: 60 * 60 * 24 * 30, // 30 days
    updateAge: 60 * 60 * 24, // refresh once per day of activity
    cookieCache: {
      enabled: true,
      maxAge: 5 * 60, // 5 min memoized session lookup
    },
  },

  user: {
    additionalFields: {
      birthDate: { type: "date", required: false },
      birthTime: { type: "string", required: false },
      gender: { type: "string", required: false },
      isLunar: { type: "boolean", required: false, defaultValue: true },
      plan: { type: "string", required: false, defaultValue: "FREE" },
      role: { type: "string", required: false, defaultValue: "USER" },
    },
  },

  trustedOrigins: [
    process.env.NEXTAUTH_URL ?? "http://localhost:3000",
    process.env.NEXT_PUBLIC_SITE_URL ?? "http://localhost:3000",
  ],
});

export type Session = typeof auth.$Infer.Session;
