import { betterAuth } from 'better-auth';
import { drizzleAdapter } from 'better-auth/adapters/drizzle';

import { db } from '@/lib/db';

/**
 * Better Auth server configuration.
 *
 * Sessions are stored in PostgreSQL (not Redis) per SECURITY-GUIDELINES.md §1.2.
 * The drizzle adapter handles session persistence via the existing `sessions` table.
 */
export const auth = betterAuth({
  database: drizzleAdapter(db, {
    provider: 'pg',
  }),

  emailAndPassword: {
    enabled: true,
    minPasswordLength: 9,
    // Accounts are admin-created only — no self-service email verification flow.
    requireEmailVerification: false,
  },

  session: {
    // Enable cookie-level session caching to reduce DB reads (5-minute cache).
    cookieCache: {
      enabled: true,
      maxAge: 5 * 60,
    },
    // Absolute session lifetime: 24 hours.
    expiresIn: 60 * 60 * 24,
    // Refresh the session whenever the user is active in the last 25% of its lifetime (6h).
    updateAge: 60 * 60 * 6,
  },

  advanced: {
    cookiePrefix: 'pn-crm',
    defaultCookieAttributes: {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'strict' as const,
    },
  },

  logger: {
    disabled: false,
    level: 'error' as const,
  },
});

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