"use server";
import { prisma } from "@/lib/prisma";
import { revalidatePath } from "next/cache";

export async function getDiscountCodes() {
  return await (prisma as any).discountCode.findMany({
    where: { deletedAt: null },
    orderBy: { createdAt: 'desc' }
  });
}

export async function saveDiscountCode(data: any) {
  try {
    const { id, ...rest } = data;
    if (rest.code) rest.code = rest.code.toUpperCase();
    const payload = { ...rest, syncStatus: 1 };
    
    if (id) {
       await (prisma as any).discountCode.update({ where: { id }, data: payload });
    } else {
       await (prisma as any).discountCode.create({ data: payload });
    }
    revalidatePath("/admin/marketing");
    return { success: true };
  } catch (error: any) {
    if (error.code === 'P2002') return { success: false, error: 'این کد تخفیف قبلا ثبت شده است.' };
    return { success: false, error: error.message };
  }
}

export async function deleteDiscountCode(id: string) {
   try {
     await (prisma as any).discountCode.update({ 
       where: { id }, 
       data: { deletedAt: new Date(), syncStatus: 1 }
     });
     revalidatePath("/admin/marketing");
     return { success: true };
   } catch(e: any) {
     return { success: false, error: e.message };
   }
}
