"use server"

import { createClient } from "@/lib/supabase/server"
import { revalidatePath } from "next/cache"
import { redirect } from "next/navigation"

export async function publishEvent(eventId: string) {
  const supabase = await createClient()
  await supabase.from("events").update({ status: "active" }).eq("id", eventId)
  revalidatePath(`/dashboard/events/${eventId}`)
}

export async function unpublishEvent(eventId: string) {
  const supabase = await createClient()
  await supabase.from("events").update({ status: "draft" }).eq("id", eventId)
  revalidatePath(`/dashboard/events/${eventId}`)
}

export async function deleteEvent(eventId: string) {
  const supabase = await createClient()

  // Check for existing orders
  const { count, error: countError } = await supabase
    .from("orders")
    .select("*", { count: "exact", head: true })
    .eq("event_id", eventId)

  if (countError) {
    return { error: "Failed to check for existing orders" }
  }

  if (count && count > 0) {
    return { error: "Cannot delete an event that has existing orders. Unpublish it instead." }
  }

  const { error: deleteError } = await supabase.from("events").delete().eq("id", eventId)

  if (deleteError) {
    return { error: "Failed to delete event" }
  }

  redirect("/dashboard")
}
