import { users } from "@prisma/client"
import { prisma } from "./prisma-client"

// Update user referral fields
export const setUserReferralData = async (
  userId: string,
  referralSource: string,
  additionalComments?: string,
): Promise<users> => {
  try {
    const result = await prisma.users.update({
      where: {
        user_id: userId,
      },
      data: {
        referral_source: referralSource,
        additional_comments: additionalComments,
      },
    })
    return result
  } catch (error) {
    console.error("Error setting user referral data:", error)
    throw error
  }
}

// Get user referral data
export const getUserReferralData = async (
  userId: string,
): Promise<Pick<users, "referral_source" | "additional_comments"> | null> => {
  try {
    const result = await prisma.users.findUnique({
      where: {
        user_id: userId,
      },
      select: {
        referral_source: true,
        additional_comments: true,
      },
    })
    return result
  } catch (error) {
    console.error("Error retrieving user referral data:", error)
    throw error
  }
}

// Check if user has completed referral
export const isUserReferralComplete = async (userId: string): Promise<boolean> => {
  try {
    const result = await prisma.users.findUnique({
      where: {
        user_id: userId,
      },
      select: {
        referral_source: true,
      },
    })
    return !!result?.referral_source
  } catch (error) {
    console.error("Error checking user referral completion:", error)
    throw error
  }
}
