"use server";
import { prisma } from "@/lib/prisma";
import { revalidatePath } from "next/cache";
import { auth } from "@/auth";
import { logSystemAction } from "./system-log";

export async function getAttributes() {
  try {
    const attributes = await prisma.attribute.findMany({
      where: { isActive: true },
      include: {
        values: { where: { isActive: true }, orderBy: { sortOrder: "asc" } },
        _count: { select: { productAttributes: true } },
        createdBy: { select: { fullName: true, phone: true } },
        updatedBy: { select: { fullName: true, phone: true } }
      },
      orderBy: { name: "asc" },
    });
    return { success: true, attributes };
  } catch (e: any) { return { success: false, attributes: [], error: e.message }; }
}

export async function createAttribute(data: {
  name: string;
  slug?: string;
  inputType: string;
  isFilterable?: boolean;
  isVariantable?: boolean;
}) {
  try {
    const session = await auth();
    const userId = session?.user?.id;

    const slug = data.slug?.trim() || data.name.toLowerCase().replace(/\s+/g, "-").replace(/[^\w\-]/g, "") + "-" + Date.now();
    const attr = await prisma.attribute.create({
      data: {
        name: data.name,
        slug,
        inputType: data.inputType as any,
        isFilterable: data.isFilterable ?? false,
        isVariantable: data.isVariantable ?? false,
        createdById: userId,
        updatedById: userId,
      },
    });
    
    if (userId) {
      await logSystemAction("CREATE_ATTRIBUTE", "Attribute", attr.id, `ایجاد ویژگی: ${attr.name}`);
    }
    
    revalidatePath("/admin/attributes");
    return { success: true, attribute: attr };
  } catch (e: any) { return { success: false, error: e.message }; }
}

export async function updateAttribute(id: string, data: { name: string; inputType?: string }) {
  try {
    const session = await auth();
    const userId = session?.user?.id;

    const attr = await prisma.attribute.update({
      where: { id },
      data: { name: data.name, inputType: data.inputType as any ?? undefined, updatedById: userId },
    });
    
    if (userId) {
      await logSystemAction("UPDATE_ATTRIBUTE", "Attribute", attr.id, `ویرایش ویژگی: ${attr.name}`);
    }
    revalidatePath("/admin/attributes");
    return { success: true, attribute: attr };
  } catch (e: any) { return { success: false, error: e.message }; }
}

export async function deleteAttribute(id: string) {
  try {
    await prisma.attribute.update({ where: { id }, data: { isActive: false } });
    revalidatePath("/admin/attributes");
    return { success: true };
  } catch { return { success: false, error: "خطا در حذف ویژگی." }; }
}

export async function createAttributeValue(attributeId: string, data: {
  value: string;
  colorHex?: string;
  featuredMediaId?: string;
}) {
  try {
    const val = await prisma.attributeValue.create({
      data: {
        attributeId,
        value: data.value,
        colorHex: data.colorHex || null,
        featuredMediaId: data.featuredMediaId || null,
        sortOrder: 0,
      },
    });
    revalidatePath("/admin/attributes");
    return { success: true, value: val };
  } catch (e: any) { return { success: false, error: e.message }; }
}

export async function deleteAttributeValue(id: string) {
  try {
    await prisma.attributeValue.delete({ where: { id } });
    revalidatePath("/admin/attributes");
    return { success: true };
  } catch { return { success: false, error: "خطا در حذف مقدار" }; }
}
