import { Client, Account, Databases, ID } from 'appwrite'

const client = new Client()

// Configure these in your .env file
const APPWRITE_ENDPOINT = import.meta.env.VITE_APPWRITE_ENDPOINT || 'https://cloud.appwrite.io/v1'
const APPWRITE_PROJECT_ID = import.meta.env.VITE_APPWRITE_PROJECT_ID || ''

client
  .setEndpoint(APPWRITE_ENDPOINT)
  .setProject(APPWRITE_PROJECT_ID)

export const account = new Account(client)
export const databases = new Databases(client)
export { ID }

// Auth helper functions
export const auth = {
  // Create a new account
  async register(email: string, password: string, name?: string) {
    try {
      const user = await account.create(ID.unique(), email, password, name)
      await this.login(email, password)
      return user
    } catch (error) {
      throw error
    }
  },

  // Login with email and password
  async login(email: string, password: string) {
    return await account.createEmailPasswordSession(email, password)
  },

  // Logout current session
  async logout() {
    return await account.deleteSession('current')
  },

  // Get current logged in user
  async getCurrentUser() {
    try {
      return await account.get()
    } catch {
      return null
    }
  },

  // Check if user is logged in
  async isLoggedIn() {
    try {
      await account.get()
      return true
    } catch {
      return false
    }
  },

  // Send password recovery email
  async forgotPassword(email: string) {
    return await account.createRecovery(
      email,
      `${window.location.origin}/reset-password`
    )
  },

  // Complete password recovery
  async resetPassword(userId: string, secret: string, newPassword: string) {
    return await account.updateRecovery(userId, secret, newPassword)
  },

  // Send verification email
  async sendVerification() {
    return await account.createVerification(
      `${window.location.origin}/verify`
    )
  },

  // Complete email verification
  async verifyEmail(userId: string, secret: string) {
    return await account.updateVerification(userId, secret)
  },
}

export default client
