import type { SupabaseClient, User } from "@supabase/supabase-js"
import type { Database } from "@/lib/supabase/database.types"
import { isAdminUser } from "@/lib/auth/is-admin"

export async function ensureUserProfile(supabase: SupabaseClient<Database>, user: User) {
  const normalizedEmail = user.email?.trim().toLowerCase() ?? ""
  if (!normalizedEmail) {
    return { ok: false as const, error: "Authenticated user has no email" }
  }

  const derivedName =
    (user.user_metadata?.full_name as string | undefined) ??
    (user.user_metadata?.name as string | undefined) ??
    normalizedEmail.split("@")[0] ??
    "Usuario"
  const role = isAdminUser(user) ? "admin" : "user"

  const { data: existingUser, error: existingUserError } = await supabase
    .from("users")
    .select("id, email, full_name, role, is_active")
    .eq("id", user.id)
    .maybeSingle()

  if (existingUserError) {
    return { ok: false as const, error: existingUserError.message }
  }

  if (!existingUser) {
    const { error: insertError } = await supabase.from("users").insert({
      id: user.id,
      email: normalizedEmail,
      full_name: derivedName,
      role,
      is_active: true,
    })

    if (insertError) {
      if (insertError.code === "23505") {
        return {
          ok: false as const,
          error: "A user profile with this email already exists under a different account",
        }
      }
      return { ok: false as const, error: insertError.message }
    }

    return { ok: true as const }
  }

  const shouldUpdate =
    existingUser.email !== normalizedEmail ||
    existingUser.full_name !== derivedName ||
    existingUser.role !== role ||
    existingUser.is_active !== true

  if (!shouldUpdate) {
    return { ok: true as const }
  }

  const { error: updateError } = await supabase
    .from("users")
    .update({
      email: normalizedEmail,
      full_name: derivedName,
      role,
      is_active: true,
    })
    .eq("id", user.id)

  if (updateError) {
    return { ok: false as const, error: updateError.message }
  }

  return { ok: true as const }
}
