"use server";
import { prisma } from "@/lib/prisma";
import { revalidatePath } from "next/cache";

export async function getOrders(params?: { status?: string; page?: number; limit?: number }) {
  try {
    const where = params?.status ? { status: params.status as any } : {};
    const orders = await (prisma as any).order.findMany({
      where,
      orderBy: { createdAt: "desc" },
      take: params?.limit || 50,
      include: {
        customer: true,
        items: { include: { product: true } },
        payments: true,
      },
    });
    return { success: true, orders };
  } catch (e: any) {
    return { success: false, orders: [], error: e.message };
  }
}

export async function getOrderById(id: string) {
  try {
    const order = await (prisma as any).order.findUnique({
      where: { id },
      include: {
        customer: true,
        items: { include: { product: true, variant: true } },
        payments: true,
        address: true,
        history: { orderBy: { createdAt: "desc" } },
      },
    });
    return { success: true, order };
  } catch (e: any) {
    return { success: false, order: null };
  }
}

export async function getCustomerOrders(customerId: string) {
  try {
    return await (prisma as any).order.findMany({
      where: { customerId },
      orderBy: { createdAt: "desc" },
      include: { items: { include: { product: true } }, payments: true },
    });
  } catch { return []; }
}

export async function updateOrderStatus(id: string, status: string) {
  try {
    const order = await (prisma as any).order.update({
      where: { id },
      data: { status: status as any },
    });
    await (prisma as any).orderStatusHistory.create({
      data: { orderId: id, status: status as any, description: "تغییر وضعیت توسط مدیر", changedBy: "ADMIN" },
    });
    revalidatePath("/admin/orders");
    return { success: true, order };
  } catch (e: any) {
    return { success: false, error: e.message };
  }
}

export async function updateOrderPaymentStatus(id: string, isPaid: boolean) {
  try {
    const order = await (prisma as any).order.update({
      where: { id },
      data: { paymentStatus: isPaid ? "PAID" : "PENDING" },
    });
    revalidatePath("/admin/orders");
    return { success: true, order, error: undefined };
  } catch (e: any) {
    return { success: false, error: e.message };
  }
}

export async function updateOrderFinancials(id: string, discount: number, shipping: number) {
  try {
    const order = await (prisma as any).order.findUnique({ where: { id } });
    if (!order) return { success: false, error: "سفارش یافت نشد." };
    const payable = order.totalPrice - discount + shipping;
    const updated = await (prisma as any).order.update({
      where: { id },
      data: { discountAmount: discount, shippingPrice: shipping, payableAmount: payable },
    });
    revalidatePath("/admin/orders");
    return { success: true, order: updated, error: undefined };
  } catch (e: any) {
    return { success: false, error: e.message };
  }
}

// POS: create order from cashier desk / barcode scan
export async function createPosOrder(data: {
  items: { productId: string; variantId?: string; qty: number; price: number; title: string }[];
  customerId?: string;
  discount?: number;
  shippingCost?: number;
  taxAmount?: number;
  note?: string;
}) {
  try {
    const totalPrice = data.items.reduce((s, i) => s + i.qty * i.price, 0);
    const discountAmount = data.discount || 0;
    const shippingPrice = data.shippingCost || 0;
    const taxAmount = data.taxAmount || 0;
    const payableAmount = totalPrice - discountAmount + shippingPrice + taxAmount;

    // Get next order code
    const last = await (prisma as any).order.findFirst({ orderBy: { orderCode: "desc" } });
    const orderCode = last ? last.orderCode + 1 : 1001;

    const order = await (prisma as any).order.create({
      data: {
        orderCode,
        channel: "POS",
        status: "DELIVERED",
        paymentStatus: "PAID",
        totalPrice,
        discountAmount,
        shippingPrice,
        taxAmount,
        payableAmount,
        note: data.note || null,
        customerId: data.customerId || null,
        items: {
          create: data.items.map(i => ({
            productId: i.productId,
            variantId: i.variantId || null,
            quantity: i.qty,
            unitPrice: i.price,
            totalPrice: i.qty * i.price,
            title: i.title,
          })),
        },
      },
      include: { items: true },
    });
    revalidatePath("/admin/orders");
    return { success: true, order };
  } catch (e: any) {
    return { success: false, error: e.message };
  }
}
