"use server";
import { prisma } from "@/lib/prisma";
import { revalidatePath } from "next/cache";

export async function getPurchases() {
  try {
    const purchases = await prisma.purchase.findMany({
      include: {
        supplier: true,
        items: {
          include: { product: true }
        }
      },
      orderBy: { purchaseDate: "desc" },
    });
    return { success: true, purchases };
  } catch (err: any) {
    console.error("Error fetching purchases:", err);
    return { success: false, error: err.message || "خطا در دریافت فاکتورهای خرید" };
  }
}

export async function getPurchaseById(id: string) {
  try {
    const purchase = await prisma.purchase.findUnique({
      where: { id },
      include: {
        supplier: true,
        items: {
          include: { product: true }
        }
      },
    });
    if (!purchase) return { success: false, error: "فاکتور یافت نشد" };
    return { success: true, purchase };
  } catch (err: any) {
    console.error("Error fetching purchase:", err);
    return { success: false, error: err.message || "خطا در دریافت فاکتور" };
  }
}

export async function createPurchase(data: { 
  supplierId: string; 
  purchaseDate: Date; 
  items: { productId: string; quantity: number; purchasePrice: number; sellingPrice?: number }[];
  discountAmount?: number;
  taxAmount?: number;
  miscAmount?: number;
  note?: string;
}) {
  try {
    const subtotal = data.items.reduce((acc, item) => acc + (item.quantity * item.purchasePrice), 0);
    const finalTotalAmount = subtotal - (data.discountAmount || 0) + (data.taxAmount || 0) + (data.miscAmount || 0);

    const purchase = await prisma.purchase.create({
      data: {
        supplierId: data.supplierId,
        purchaseDate: data.purchaseDate,
        totalAmount: finalTotalAmount,
        discountAmount: data.discountAmount || 0,
        taxAmount: data.taxAmount || 0,
        miscAmount: data.miscAmount || 0,
        note: data.note || "",
        items: {
          create: data.items.map(item => ({
            productId: item.productId,
            quantity: item.quantity,
            purchasePrice: item.purchasePrice,
          })),
        },
      },
    });

    // Update supplier balance
    await prisma.supplier.update({
      where: { id: data.supplierId },
      data: {
        balance: {
          increment: finalTotalAmount
        }
      }
    });

    // Update product stock and price
    for (const item of data.items) {
      const productUpdateData: any = {
        stockQuantity: {
          increment: item.quantity
        }
      };
      
      if (item.sellingPrice !== undefined && item.sellingPrice > 0) {
        productUpdateData.price = item.sellingPrice;
      }

      await prisma.product.update({
        where: { id: item.productId },
        data: productUpdateData
      });
      
      // Create stock adjustment
      await (prisma as any).stockAdjustment.create({
        data: {
          productId: item.productId,
          type: "ADD",
          quantity: item.quantity,
          reason: `خرید از تامین‌کننده (فاکتور ${purchase.id.slice(0, 8)})`,
          changedBy: "ADMIN"
        }
      });
    }

    revalidatePath("/admin/purchases");
    revalidatePath("/admin/products");
    revalidatePath("/admin/suppliers");
    
    return { success: true, purchase };
  } catch (err: any) {
    console.error("Error creating purchase:", err);
    return { success: false, error: err.message || "خطا در ثبت فاکتور خرید" };
  }
}

export async function deletePurchase(id: string) {
  try {
    // Note: We should ideally revert the stock and balance, but for now we just delete
    await prisma.purchase.delete({
      where: { id },
    });
    revalidatePath("/admin/purchases");
    return { success: true };
  } catch (err: any) {
    console.error("Error deleting purchase:", err);
    return { success: false, error: err.message || "خطا در حذف فاکتور خرید" };
  }
}
