'use server'

import { auth } from '@/auth'
import { prisma } from '@/lib/prisma'
import { revalidatePath } from 'next/cache'

export async function saveCanvas(id: string | null, name: string, data: string) {
  const session = await auth()
  if (!session?.user?.id) throw new Error('Unauthorized')

  if (id) {
    const canvas = await prisma.canvas.update({
      where: { id, userId: session.user.id },
      data: { name, data }
    })
    revalidatePath('/lab')
    return { success: true, canvas }
  } else {
    const canvas = await prisma.canvas.create({
      data: {
        name,
        data,
        userId: session.user.id
      }
    })
    revalidatePath('/lab')
    return { success: true, canvas }
  }
}

export async function getCanvases() {
  const session = await auth()
  if (!session?.user?.id) return []

  return prisma.canvas.findMany({
    where: { userId: session.user.id },
    orderBy: { createdAt: 'asc' }
  })
}

export async function getCanvasDetails(id: string) {
  const session = await auth()
  if (!session?.user?.id) return null

  return prisma.canvas.findUnique({
    where: { id, userId: session.user.id }
  })
}

export async function deleteCanvas(id: string) {
  const session = await auth()
  if (!session?.user?.id) throw new Error('Unauthorized')

  await prisma.canvas.delete({
    where: { id, userId: session.user.id }
  })

  revalidatePath('/lab')
  return { success: true }
}

export async function renameCanvas(id: string, name: string) {
  const session = await auth()
  if (!session?.user?.id) throw new Error('Unauthorized')

  await prisma.canvas.update({
    where: { id, userId: session.user.id },
    data: { name }
  })

  revalidatePath('/lab')
  return { success: true }
}

export async function createCanvas(lang?: string) {
  const session = await auth()
  if (!session?.user?.id) throw new Error('Unauthorized')

  const count = await prisma.canvas.count({
    where: { userId: session.user.id }
  })

  const defaultNames: Record<string, string> = {
    en: `Space ${count + 1}`,
    fr: `Espace ${count + 1}`,
    fa: `فضای ${count + 1}`,
    es: `Espacio ${count + 1}`,
    de: `Bereich ${count + 1}`,
    it: `Spazio ${count + 1}`,
    pt: `Espaço ${count + 1}`,
    ru: `Пространство ${count + 1}`,
    ja: `スペース ${count + 1}`,
    ko: `공간 ${count + 1}`,
    zh: `空间 ${count + 1}`,
    ar: `مساحة ${count + 1}`,
    hi: `स्थान ${count + 1}`,
    nl: `Ruimte ${count + 1}`,
    pl: `Przestrzeń ${count + 1}`,
  }

  const newCanvas = await prisma.canvas.create({
    data: {
      name: defaultNames[lang || 'en'] || defaultNames.en,
      data: JSON.stringify({}),
      userId: session.user.id
    }
  })

  revalidatePath('/lab')
  return newCanvas
}
