"use server";
import { prisma } from "@/lib/prisma";
import { revalidatePath } from "next/cache";

export async function getShippingMethods() {
  try {
    const methods = await prisma.shippingMethod.findMany({
      include: { iconMedia: true },
      orderBy: { sortOrder: "asc" }
    });
    return { success: true, methods };
  } catch (e: any) {
    return { success: false, error: e.message };
  }
}

export async function createShippingMethod(data: any) {
  try {
    const method = await prisma.shippingMethod.create({
      data: {
        name: data.name,
        description: data.description,
        baseCost: parseInt(data.baseCost) || 0,
        baseCostCity: data.baseCostCity ? parseInt(data.baseCostCity) : null,
        baseCostProvince: data.baseCostProvince ? parseInt(data.baseCostProvince) : null,
        costPerKg: parseInt(data.costPerKg) || 0,
        extraCostPerItem: parseInt(data.extraCostPerItem) || 0,
        freeShippingThreshold: data.freeShippingThreshold ? parseInt(data.freeShippingThreshold) : null,
        iconMediaId: data.iconMediaId || null,
        isPayOnDelivery: data.isPayOnDelivery || false,
        isActive: data.isActive !== undefined ? data.isActive : true,
        sortOrder: parseInt(data.sortOrder) || 0,
      }
    });
    revalidatePath("/admin/shipping");
    return { success: true, method };
  } catch (e: any) {
    return { success: false, error: e.message };
  }
}

export async function updateShippingMethod(id: string, data: any) {
  try {
    const method = await prisma.shippingMethod.update({
      where: { id },
      data: {
        name: data.name,
        description: data.description,
        baseCost: parseInt(data.baseCost) || 0,
        baseCostCity: data.baseCostCity ? parseInt(data.baseCostCity) : null,
        baseCostProvince: data.baseCostProvince ? parseInt(data.baseCostProvince) : null,
        costPerKg: parseInt(data.costPerKg) || 0,
        extraCostPerItem: parseInt(data.extraCostPerItem) || 0,
        freeShippingThreshold: data.freeShippingThreshold ? parseInt(data.freeShippingThreshold) : null,
        iconMediaId: data.iconMediaId || null,
        isPayOnDelivery: data.isPayOnDelivery || false,
        isActive: data.isActive !== undefined ? data.isActive : true,
        sortOrder: parseInt(data.sortOrder) || 0,
      }
    });
    revalidatePath("/admin/shipping");
    return { success: true, method };
  } catch (e: any) {
    return { success: false, error: e.message };
  }
}

export async function deleteShippingMethod(id: string) {
  try {
    await prisma.shippingMethod.delete({
      where: { id }
    });
    revalidatePath("/admin/shipping");
    return { success: true };
  } catch (e: any) {
    return { success: false, error: "این روش ارسال احتمالا در سفارشات استفاده شده و قابل حذف نیست." };
  }
}
