"use server"

import { CreateUserParams, InviteUserParams, UpdateUserParams, User } from "@/src/models/users/users.model"
import { createClient } from "@supabase/supabase-js"


// Initialize Supabase client with admin key
const supabase = createClient(process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.SERVICE_ROLE_SECRET!, {
  auth: {
    autoRefreshToken: false,
    persistSession: false,
  },
})

// Fetch all users
export async function fetchUsers(): Promise<User[]> {
  const { data, error } = await supabase.auth.admin.listUsers()

  if (error) {
    console.error("Error fetching users:", error)
    throw new Error(error.message)
  }

  return data.users.map(user => ({
    ...user,
    updated_at: user.updated_at || "",
  })) as User[]
}

// Create a new user
export async function createUser(params: CreateUserParams): Promise<User> {
  const { data, error } = await supabase.auth.admin.createUser({
    email: params.email,
    password: params.password,
    phone: params.phone,
    user_metadata: params.user_metadata,
    email_confirm: params.email_confirm,
  })

  if (error) {
    console.error("Error creating user:", error)
    throw new Error(error.message)
  }

  return {
    ...data.user,
    updated_at: data.user.updated_at || "",
  } as User
}

// Update an existing user
export async function updateUser(userId: string, params: UpdateUserParams): Promise<User> {
  const { data, error } = await supabase.auth.admin.updateUserById(userId, {
    email: params.email,
    phone: params.phone,
    password: params.password,
    user_metadata: params.user_metadata,
  })

  if (error) {
    console.error("Error updating user:", error)
    throw new Error(error.message)
  }

  return {
    ...data.user,
    updated_at: data.user.updated_at || "",
  } as User
}

// Delete a user
export async function deleteUser(userId: string): Promise<void> {
  const { error } = await supabase.auth.admin.deleteUser(userId)

  if (error) {
    console.error("Error deleting user:", error)
    throw new Error(error.message)
  }
}

// Send password recovery email
export async function sendPasswordRecovery(email: string): Promise<void> {
  const { error } = await supabase.auth.resetPasswordForEmail(email, {
    redirectTo: `${process.env.NEXT_PUBLIC_SITE_URL}/auth/reset-password`,
  })

  if (error) {
    console.error("Error sending password recovery:", error)
    throw new Error(error.message)
  }
}

// Send magic link
export async function sendMagicLink(email: string): Promise<void> {
  const { error } = await supabase.auth.signInWithOtp({
    email,
    options: {
      emailRedirectTo: `${process.env.NEXT_PUBLIC_SITE_URL}/auth/callback`,
    },
  })

  if (error) {
    console.error("Error sending magic link:", error)
    throw new Error(error.message)
  }
}

// Ban a user
export async function banUser(userId: string): Promise<User> {
  // Ban for 100 years (effectively permanent)
  const banUntil = new Date()
  banUntil.setFullYear(banUntil.getFullYear() + 100)

  const { data, error } = await supabase.auth.admin.updateUserById(userId, {
    ban_duration: "100h",
  })

  if (error) {
    console.error("Error banning user:", error)
    throw new Error(error.message)
  }

  return {
    ...data.user,
    updated_at: data.user.updated_at || "",
  } as User
}

// Unban a user
export async function unbanUser(userId: string): Promise<User> {
  const { data, error } = await supabase.auth.admin.updateUserById(userId, {
    ban_duration: "none",
  })

  if (error) {
    console.error("Error unbanning user:", error)
    throw new Error(error.message)
  }

  return {
    ...data.user,
    updated_at: data.user.updated_at || "",
  } as User
}

// Invite a user
export async function inviteUser(params: InviteUserParams): Promise<void> {
  const { error } = await supabase.auth.admin.inviteUserByEmail(params.email, {
    data: params.user_metadata,
    redirectTo: `${process.env.NEXT_PUBLIC_SITE_URL}/auth/callback`,
  })

  if (error) {
    console.error("Error inviting user:", error)
    throw new Error(error.message)
  }
}

