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

import { db } from './db/client';
import { schema } from './db/schema';
import { getBetterAuthBaseUrl, getRequiredEnv } from './utils/env';
import { hashPassword, verifyPassword } from './utils/password';

const trustedOrigins = process.env.BETTER_AUTH_TRUSTED_ORIGINS
  ? process.env.BETTER_AUTH_TRUSTED_ORIGINS.split(',').map((origin) => origin.trim()).filter(Boolean)
  : undefined;

export const auth = betterAuth({
  database: drizzleAdapter(db, {
    provider: 'pg',
    schema: {
      ...schema,
      user: schema.users,
      account: schema.accounts,
      session: schema.sessions,
      verification: schema.verifications,
    },
  }),
  advanced: {
    database: {
      generateId: 'uuid',
    },
  },
  emailAndPassword: {
    enabled: true,
    password: {
      hash: async (password) => hashPassword(password),
      verify: async ({ hash, password }) => verifyPassword(password, hash),
    },
  },
  secret: getRequiredEnv('BETTER_AUTH_SECRET'),
  baseURL: getBetterAuthBaseUrl(),
  trustedOrigins,
});

export type AuthSession = Awaited<ReturnType<typeof auth.api.getSession>>;
