'use server'

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

export async function createProduct(_prevState: unknown, formData: FormData) {
  const name_tr = formData.get('name_tr') as string
  const name = formData.get('name') as string || name_tr
  const price = parseFloat(formData.get('price') as string)
  const category_id = parseInt(formData.get('category_id') as string, 10)
  const description_tr = formData.get('description_tr') as string || ''
  const image_url = formData.get('image_url') as string || null
  const status = formData.get('status') === 'on' ? 1 : 0

  if (!name_tr || isNaN(price) || isNaN(category_id)) {
    return { error: 'Lütfen zorunlu alanları doldurun.' }
  }

  try {
    await prisma.products.create({
      data: {
        name,
        name_tr,
        slug: name_tr.toLowerCase().replace(/[^a-z0-9]+/g, '-'),
        price,
        category_id,
        description_tr,
        image_url,
        status,
      }
    })
  } catch (error) {
    console.error('Create product error:', error)
    return { error: 'Ürün eklenirken hata oluştu.' }
  }

  revalidatePath('/admin/products')
  revalidatePath('/')
  redirect('/admin/products')
}

export async function updateProduct(id: number, _prevState: unknown, formData: FormData) {
  const name_tr = formData.get('name_tr') as string
  const name = formData.get('name') as string || name_tr
  const price = parseFloat(formData.get('price') as string)
  const category_id = parseInt(formData.get('category_id') as string, 10)
  const description_tr = formData.get('description_tr') as string || ''
  const image_url = formData.get('image_url') as string || null
  const status = formData.get('status') === 'on' ? 1 : 0

  if (!name_tr || isNaN(price) || isNaN(category_id)) {
    return { error: 'Lütfen zorunlu alanları doldurun.' }
  }

  try {
    await prisma.products.update({
      where: { id },
      data: {
        name,
        name_tr,
        slug: name_tr.toLowerCase().replace(/[^a-z0-9]+/g, '-'),
        price,
        category_id,
        description_tr,
        image_url,
        status,
      }
    })
  } catch (error) {
    console.error('Update product error:', error)
    return { error: 'Ürün güncellenirken hata oluştu.' }
  }

  revalidatePath('/admin/products')
  revalidatePath('/')
  redirect('/admin/products')
}

export async function deleteProduct(id: number) {
  try {
    await prisma.products.delete({
      where: { id }
    })
    revalidatePath('/admin/products')
    revalidatePath('/')
    return { success: true }
  } catch (error) {
    console.error('Delete product error:', error)
    return { error: 'Silme işlemi başarısız oldu.' }
  }
}
