"use server";

import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { prisma } from "@/lib/prisma";
import { requirePermission } from "@/lib/permissions";

function revalidateStorefront() {
  revalidatePath("/shop");
  revalidatePath("/");
}

// ---------- Coupon Codes ----------

export async function createCoupon(formData: FormData) {
  await requirePermission("discounts", "add");
  const code = String(formData.get("code") ?? "").trim().toUpperCase();
  const type = String(formData.get("type") ?? "percent");
  const valueRaw = Number(formData.get("value") ?? 0);
  const minOrderRaw = String(formData.get("minOrderValue") ?? "").trim();
  const minOrderRawNum = minOrderRaw ? Number(minOrderRaw) : 0;
  const maxUsesRaw = String(formData.get("maxUses") ?? "").trim();
  const maxUsesRawNum = maxUsesRaw ? Number(maxUsesRaw) : 0;

  if (!code) redirect("/iv-manage-84x2/discounts?error=Coupon+code+is+required");
  if (code.length > 30) redirect("/iv-manage-84x2/discounts?error=Coupon+code+is+too+long");
  if (!Number.isFinite(valueRaw) || (minOrderRaw && !Number.isFinite(minOrderRawNum)) || (maxUsesRaw && !Number.isFinite(maxUsesRawNum))) {
    redirect("/iv-manage-84x2/discounts?error=Enter+valid+numbers");
  }

  const value = type === "percent" ? Math.min(90, Math.max(1, Math.round(valueRaw))) : Math.max(1, Math.round(valueRaw * 100));
  const minOrderValue = minOrderRaw ? Math.round(minOrderRawNum * 100) : null;
  const maxUses = maxUsesRaw ? Math.max(1, Math.round(maxUsesRawNum)) : null;
  const expiresAtRaw = String(formData.get("expiresAt") ?? "").trim();
  const expiresAt = expiresAtRaw ? new Date(expiresAtRaw) : null;
  const oneUsePerCustomer = formData.get("oneUsePerCustomer") === "on";

  const existing = await prisma.coupon.findUnique({ where: { code } });
  if (existing) redirect("/iv-manage-84x2/discounts?error=That+coupon+code+already+exists");

  await prisma.coupon.create({ data: { code, type, value, minOrderValue, maxUses, expiresAt, oneUsePerCustomer } });
  revalidatePath("/iv-manage-84x2/discounts");
  redirect("/iv-manage-84x2/discounts?success=Coupon+created.");
}

export async function toggleCoupon(id: string) {
  await requirePermission("discounts", "edit");
  const coupon = await prisma.coupon.findUniqueOrThrow({ where: { id } });
  await prisma.coupon.update({ where: { id }, data: { active: !coupon.active } });
  revalidatePath("/iv-manage-84x2/discounts");
  redirect("/iv-manage-84x2/discounts?success=Coupon+updated.");
}

export async function deleteCoupon(id: string) {
  await requirePermission("discounts", "delete");
  await prisma.coupon.delete({ where: { id } });
  revalidatePath("/iv-manage-84x2/discounts");
  redirect("/iv-manage-84x2/discounts?success=Coupon+deleted.");
}

// ---------- Buy X Get Y ----------

function parseTarget(raw: string): { productId: string | null; categoryId: string | null } | null {
  const [type, id] = raw.split(":");
  if (!id) return null;
  if (type === "product") return { productId: id, categoryId: null };
  if (type === "category") return { productId: null, categoryId: id };
  return null;
}

export async function createBuyXGetYOffer(formData: FormData) {
  await requirePermission("discounts", "add");
  const name = String(formData.get("name") ?? "").trim();
  const target = parseTarget(String(formData.get("target") ?? ""));
  const buyQtyRaw = Number(formData.get("buyQty") ?? 0);
  const getQtyRaw = Number(formData.get("getQty") ?? 0);
  const getDiscountPctRaw = Number(formData.get("getDiscountPct") ?? 100);

  if (!name || !target) {
    redirect("/iv-manage-84x2/discounts/buy-x-get-y?error=Fill+in+name%2C+target%2C+and+quantities");
  }
  if (!Number.isFinite(buyQtyRaw) || !Number.isFinite(getQtyRaw) || !Number.isFinite(getDiscountPctRaw)) {
    redirect("/iv-manage-84x2/discounts/buy-x-get-y?error=Enter+valid+numbers");
  }
  const buyQty = Math.max(1, Math.round(buyQtyRaw));
  const getQty = Math.max(1, Math.round(getQtyRaw));
  const getDiscountPct = Math.min(100, Math.max(1, Math.round(getDiscountPctRaw)));

  await prisma.buyXGetYOffer.create({
    data: {
      name,
      productId: target!.productId,
      categoryId: target!.categoryId,
      buyQty,
      getQty,
      getDiscountPct,
    },
  });
  revalidatePath("/iv-manage-84x2/discounts/buy-x-get-y");
  revalidateStorefront();
  redirect("/iv-manage-84x2/discounts/buy-x-get-y?success=Offer+created.");
}

export async function toggleBuyXGetYOffer(id: string) {
  await requirePermission("discounts", "edit");
  const offer = await prisma.buyXGetYOffer.findUniqueOrThrow({ where: { id } });
  await prisma.buyXGetYOffer.update({ where: { id }, data: { active: !offer.active } });
  revalidatePath("/iv-manage-84x2/discounts/buy-x-get-y");
  redirect("/iv-manage-84x2/discounts/buy-x-get-y?success=Offer+updated.");
}

export async function deleteBuyXGetYOffer(id: string) {
  await requirePermission("discounts", "delete");
  await prisma.buyXGetYOffer.delete({ where: { id } });
  revalidatePath("/iv-manage-84x2/discounts/buy-x-get-y");
  redirect("/iv-manage-84x2/discounts/buy-x-get-y?success=Offer+deleted.");
}

// ---------- Bulk Order Discounts ----------

export async function createBulkTier(formData: FormData) {
  await requirePermission("discounts", "add");
  const target = parseTarget(String(formData.get("target") ?? ""));
  const minQtyRaw = Number(formData.get("minQty") ?? 0);
  const discountPercentRaw = Number(formData.get("discountPercent") ?? 0);

  if (!target) {
    redirect("/iv-manage-84x2/discounts/bulk?error=Pick+a+product+or+category");
  }
  if (!Number.isFinite(minQtyRaw) || !Number.isFinite(discountPercentRaw)) {
    redirect("/iv-manage-84x2/discounts/bulk?error=Enter+valid+numbers");
  }
  const minQty = Math.max(2, Math.round(minQtyRaw));
  const discountPercent = Math.min(90, Math.max(1, Math.round(discountPercentRaw)));

  await prisma.bulkDiscountTier.create({
    data: {
      productId: target!.productId,
      categoryId: target!.categoryId,
      minQty,
      discountPercent,
    },
  });
  revalidatePath("/iv-manage-84x2/discounts/bulk");
  revalidateStorefront();
  redirect("/iv-manage-84x2/discounts/bulk?success=Bulk+discount+tier+created.");
}

export async function toggleBulkTier(id: string) {
  await requirePermission("discounts", "edit");
  const tier = await prisma.bulkDiscountTier.findUniqueOrThrow({ where: { id } });
  await prisma.bulkDiscountTier.update({ where: { id }, data: { active: !tier.active } });
  revalidatePath("/iv-manage-84x2/discounts/bulk");
  redirect("/iv-manage-84x2/discounts/bulk?success=Bulk+discount+tier+updated.");
}

export async function deleteBulkTier(id: string) {
  await requirePermission("discounts", "delete");
  await prisma.bulkDiscountTier.delete({ where: { id } });
  revalidatePath("/iv-manage-84x2/discounts/bulk");
  redirect("/iv-manage-84x2/discounts/bulk?success=Bulk+discount+tier+deleted.");
}

// ---------- Festival Offers ----------

export async function createFestivalOffer(formData: FormData) {
  await requirePermission("discounts", "add");
  const name = String(formData.get("name") ?? "").trim();
  const discountPercentRaw = Number(formData.get("discountPercent") ?? 0);
  const startsAtRaw = String(formData.get("startsAt") ?? "").trim();
  const endsAtRaw = String(formData.get("endsAt") ?? "").trim();

  if (!name || !startsAtRaw || !endsAtRaw) {
    redirect("/iv-manage-84x2/discounts/festival?error=Fill+in+name+and+both+dates");
  }
  if (!Number.isFinite(discountPercentRaw)) {
    redirect("/iv-manage-84x2/discounts/festival?error=Enter+a+valid+discount+percent");
  }
  const discountPercent = Math.min(90, Math.max(1, Math.round(discountPercentRaw)));
  const startsAt = new Date(startsAtRaw);
  const endsAt = new Date(endsAtRaw);
  if (endsAt <= startsAt) {
    redirect("/iv-manage-84x2/discounts/festival?error=End+date+must+be+after+start+date");
  }

  await prisma.festivalOffer.create({ data: { name, discountPercent, startsAt, endsAt } });
  revalidatePath("/iv-manage-84x2/discounts/festival");
  revalidateStorefront();
  redirect("/iv-manage-84x2/discounts/festival?success=Festival+offer+created.");
}

export async function toggleFestivalOffer(id: string) {
  await requirePermission("discounts", "edit");
  const offer = await prisma.festivalOffer.findUniqueOrThrow({ where: { id } });
  await prisma.festivalOffer.update({ where: { id }, data: { active: !offer.active } });
  revalidatePath("/iv-manage-84x2/discounts/festival");
  redirect("/iv-manage-84x2/discounts/festival?success=Festival+offer+updated.");
}

export async function deleteFestivalOffer(id: string) {
  await requirePermission("discounts", "delete");
  await prisma.festivalOffer.delete({ where: { id } });
  revalidatePath("/iv-manage-84x2/discounts/festival");
  redirect("/iv-manage-84x2/discounts/festival?success=Festival+offer+deleted.");
}
