"use server";
import { prisma } from "@/lib/prisma";
import { revalidatePath } from "next/cache";
import { auth } from "@/auth";
import { logSystemAction } from "./system-log";

export async function getCategories() {
  try {
    const cats = await prisma.category.findMany({
      where: { isActive: true },
      orderBy: [{ sortOrder: "asc" }, { name: "asc" }],
      include: { 
        children: true, 
        _count: { select: { products: true } },
        createdBy: { select: { fullName: true, phone: true } },
        updatedBy: { select: { fullName: true, phone: true } }
      },
    });
    return { success: true, categories: cats };
  } catch (e: any) {
    return { success: false, categories: [], error: e.message };
  }
}

export async function createCategory(data: any) {
  try {
    const session = await auth();
    const userId = session?.user?.id;
    
    const slug = data.slug || data.name.toLowerCase().replace(/\s+/g, "-").replace(/[^\w\-]/g, "") + "-" + Date.now();
    const cat = await prisma.category.create({
      data: {
        name: data.name,
        slug: slug || data.slug,
        description: data.description || null,
        parentId: data.parentId || null,
        imageMediaId: data.imageMediaId || null,
        sortOrder: data.sortOrder || 0,
        syncStatus: 1,
        createdById: userId,
        updatedById: userId,
      } as any,
    });
    
    if (userId) {
      await logSystemAction("CREATE_CATEGORY", "Category", cat.id, `ایجاد دسته‌بندی: ${cat.name}`);
    }
    
    revalidatePath("/admin/categories");
    return { success: true, category: cat };
  } catch (e: any) {
    return { success: false, error: "خطا در ایجاد دسته‌بندی: " + e.message };
  }
}

export async function updateCategory(id: string, data: any) {
  try {
    const session = await auth();
    const userId = session?.user?.id;
    
    const cat = await prisma.category.update({
      where: { id },
      data: {
        name: data.name,
        description: data.description || null,
        parentId: data.parentId || null,
        imageMediaId: data.imageMediaId || null,
        sortOrder: data.sortOrder || 0,
        syncStatus: 2,
        updatedById: userId,
      } as any,
    });
    
    if (userId) {
      await logSystemAction("UPDATE_CATEGORY", "Category", cat.id, `ویرایش دسته‌بندی: ${cat.name}`);
    }
    
    revalidatePath("/admin/categories");
    return { success: true, category: cat };
  } catch (e: any) {
    return { success: false, error: "خطا در ویرایش دسته‌بندی." };
  }
}

export async function deleteCategory(id: string) {
  try {
    const hasProducts = await prisma.productCategory.count({ where: { categoryId: id } });
    if (hasProducts > 0) return { success: false, error: "این دسته‌بندی دارای محصول است. ابتدا محصولات آن را منتقل کنید." };
    await prisma.category.delete({ where: { id } });
    revalidatePath("/admin/categories");
    return { success: true };
  } catch (e: any) {
    return { success: false, error: "خطا در حذف دسته‌بندی." };
  }
}
