"use server"
import { getUserPrivacyMode, setUserPrivacyMode, isUserPaid, prisma } from "@codeflash-ai/common"
import { updateTag } from "next/cache"
import { dedup } from "@/lib/request-dedup"
import * as Sentry from "@sentry/nextjs"

export async function getPrivacyMode(userId: string): Promise<boolean> {
  return dedup(`privacy:${userId}`, async () => {
    try {
      return await getUserPrivacyMode(userId)
    } catch (error) {
      console.error("Error getting privacy mode:", error)
      Sentry.captureException(error)
      return false
    }
  })
}

export async function updatePrivacyMode(userId: string, privacyMode: boolean): Promise<boolean> {
  try {
    await setUserPrivacyMode(userId, privacyMode)
    updateTag(`dashboard:${userId}`)
    return true
  } catch (error) {
    console.error("Error updating privacy mode:", error)
    Sentry.captureException(error)
    return false
  }
}

export async function checkCanUsePrivacyMode(userId: string): Promise<boolean> {
  return dedup(`can-privacy:${userId}`, async () => {
    try {
      return await isUserPaid(userId)
    } catch (error) {
      console.error("Error checking if user can use privacy mode:", error)
      Sentry.captureException(error)
      return false
    }
  })
}

// Organization privacy mode functions
export async function getOrgPrivacyMode(organizationId: string): Promise<boolean> {
  try {
    const org = await prisma.organizations.findUnique({
      where: { id: organizationId },
      select: { privacy_mode: true },
    })
    return org?.privacy_mode ?? false
  } catch (error) {
    console.error("Error getting org privacy mode:", error)
    Sentry.captureException(error)
    return false
  }
}

export async function updateOrgPrivacyMode(
  userId: string,
  organizationId: string,
  privacyMode: boolean,
): Promise<{ success: boolean; error?: string }> {
  try {
    // Check if user is admin or owner (uses unique composite index)
    const member = await prisma.organization_members.findUnique({
      where: {
        organization_id_user_id: { organization_id: organizationId, user_id: userId },
      },
      select: { role: true },
    })

    if (!member || (member.role !== "admin" && member.role !== "owner")) {
      return { success: false, error: "Only admins can change organization privacy settings" }
    }

    await prisma.organizations.update({
      where: { id: organizationId },
      data: { privacy_mode: privacyMode },
    })

    updateTag(`dashboard:${userId}`)
    return { success: true }
  } catch (error) {
    console.error("Error updating org privacy mode:", error)
    Sentry.captureException(error)
    return { success: false, error: "Failed to update privacy mode" }
  }
}

export async function checkOrgCanUsePrivacyMode(organizationId: string): Promise<boolean> {
  try {
    const org = await prisma.organizations.findUnique({
      where: { id: organizationId },
      select: { subscription: true },
    })
    return org?.subscription ?? false
  } catch (error) {
    console.error("Error checking if org can use privacy mode:", error)
    Sentry.captureException(error)
    return false
  }
}
