"use server"
import { prisma } from "./prisma-client"
import { SUBSCRIPTION_PLANS } from "./subscription-config"

export async function createOrUpdateUser(
  user_id: string,
  github_username: string,
  email: string | null,
  name: string | null,
) {
  const user = await prisma.users.upsert({
    where: { user_id },
    update: { email, github_username, name },
    create: { user_id, email, github_username, name },
  })

  // Create free subscription if user was newly created and doesn't have one
  const existingSubscription = await prisma.subscriptions.findUnique({
    where: { user_id },
  })

  if (!existingSubscription) {
    try {
      await prisma.subscriptions.create({
        data: {
          user_id: user_id,
          plan_type: "FREE",
          optimizations_limit: SUBSCRIPTION_PLANS.FREE.optimizations,
          subscription_status: "active",
          optimizations_used: 0,
        },
      })
      console.log(`[UserFunction] Created free subscription for user: ${user_id}`)
    } catch (error) {
      // Handle race condition where subscription was created by another request
      if (
        error instanceof Error &&
        error.message.includes("duplicate key value violates unique constraint")
      ) {
        console.log(`[UserFunction] Subscription already exists for user: ${user_id}`)
      } else {
        console.error(`[UserFunction] Failed to create subscription for user ${user_id}:`, error)
        // Don't throw error - user creation should succeed even if subscription fails
      }
    }
  }

  return user
}

export async function hasCompletedOnboarding(user_id: string): Promise<boolean> {
  const user = await prisma.users.findUnique({
    where: { user_id },
    select: { onboarding_completed: true },
  })
  return user?.onboarding_completed ?? false
}

export async function markUserCompletedOnboarding(user_id: string): Promise<void> {
  await prisma.users.update({
    where: { user_id },
    data: { onboarding_completed: true },
  })
}

export async function submitOnboardingQuestions(user_id: string, email: string): Promise<void> {
  await prisma.users.update({
    where: { user_id },
    data: { email, onboarding_completed: true },
  })
}

export async function getUserById(userId: string) {
  return prisma.users.findUnique({
    where: {
      user_id: userId,
    },
  })
}

export async function getUserPrivacyMode(user_id: string): Promise<boolean> {
  const user = await prisma.users.findUnique({
    where: { user_id },
    select: { privacy_mode: true },
  })
  return user?.privacy_mode ?? false
}

export async function setUserPrivacyMode(user_id: string, privacy_mode: boolean): Promise<void> {
  await prisma.users.update({
    where: { user_id },
    data: { privacy_mode },
  })
}

export async function isUserPaid(user_id: string): Promise<boolean> {
  const subscription = await prisma.subscriptions.findUnique({
    where: { user_id },
    select: { plan_type: true, subscription_status: true },
  })

  if (!subscription) {
    return false
  }

  const planType = subscription.plan_type.toUpperCase()
  return subscription.subscription_status === "active" && planType !== "FREE"
}
