import { createAuthClient } from 'better-auth/client'
import { organizationClient } from 'better-auth/client/plugins'
import { apiUrl } from './env'

// Better Auth mounts at /api/auth (default basePath); the client appends the
// endpoint verbatim to baseURL, so the base must include /auth — otherwise it
// emits /api/sign-in/email and 404s on both sandbox and deploy.
export const authClient = createAuthClient({
  baseURL: `${apiUrl()}/auth`,
  plugins: [organizationClient()],
})

export const INVALID_CREDENTIALS = 'INVALID_CREDENTIALS'
export const EMAIL_IN_USE = 'EMAIL_IN_USE'

export async function signInWithPassword(email: string, password: string): Promise<void> {
  const { error } = await authClient.signIn.email({ email, password })
  if (error) throw new Error(INVALID_CREDENTIALS)
}

export async function registerWithPassword(
  email: string,
  password: string,
  name: string,
): Promise<void> {
  const { error } = await authClient.signUp.email({
    email,
    password,
    name: name.trim() || email.split('@')[0],
  })
  if (error) {
    if (error.status === 422 || /exist|taken/i.test(error.message ?? '')) {
      throw new Error(EMAIL_IN_USE)
    }
    throw new Error('Unable to create account')
  }
}

export async function signOut(): Promise<void> {
  await authClient.signOut()
}
