"use server";

import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { prisma } from "@/lib/prisma";
import { priceWithMarkup } from "@/lib/utils";

function toNonNegativeNumber(value: FormDataEntryValue | null, fallback = 0) {
  const normalized = String(value ?? fallback).replace(",", ".").trim();
  const parsed = Number(normalized);
  return Number.isFinite(parsed) ? Math.max(0, parsed) : fallback;
}

function toBoundedScore(value: FormDataEntryValue | null, fallback = 3) {
  const parsed = Number(value ?? fallback);
  if (!Number.isFinite(parsed)) return fallback;
  return Math.min(5, Math.max(1, Math.round(parsed)));
}

function normalizeImagePath(value: FormDataEntryValue | null) {
  const image = String(value || "").trim();
  return image || "/products/gold-bar.svg";
}

export async function createProduct(form: FormData) {
  const pricingMode = String(form.get("pricingMode") || "DIRECT_MANUAL");
  const manualPrice = Number(form.get("manualPrice") || 0);
  const supplierPrice = Number(form.get("supplierPrice") || 0);
  const markupPercent = Number(form.get("markupPercent") || 10);
  const customerPrice = pricingMode === "SUPPLIER_MARKUP" ? priceWithMarkup(supplierPrice, markupPercent) : manualPrice;
  const image = normalizeImagePath(form.get("image"));
  const itemKind = String(form.get("itemKind") || "PHYSICAL_BULLION");
  const premiumPercent = toNonNegativeNumber(form.get("premiumPercent"));
  const spreadPercent = toNonNegativeNumber(form.get("spreadPercent"));
  const liquidityScore = toBoundedScore(form.get("liquidityScore"));
  const shippingSpeedScore = toBoundedScore(form.get("shippingSpeedScore"));
  await prisma.product.create({
    data: {
      name: String(form.get("name")),
      slug: String(form.get("slug")),
      metalType: String(form.get("metalType")),
      weight: String(form.get("weight")),
      purity: String(form.get("purity")),
      karat: String(form.get("karat") || "") || null,
      productType: String(form.get("productType")),
      itemKind,
      isPublicProduct: itemKind === "PHYSICAL_BULLION",
      isServiceItem: itemKind === "SERVICE",
      mintBrand: String(form.get("mintBrand")),
      brandMint: String(form.get("brandMint") || form.get("mintBrand")),
      supplierId: String(form.get("supplierId")),
      categoryId: String(form.get("categoryId") || "") || null,
      pricingMode,
      manualPrice,
      supplierPrice,
      markupPercent,
      customerPrice,
      totalSalePrice: customerPrice,
      shortDescription: String(form.get("shortDescription") || ""),
      description: String(form.get("description")),
      imageUrls: JSON.stringify([image]),
      images: JSON.stringify([image]),
      inventoryStatus: String(form.get("stockStatus")),
      stockStatus: String(form.get("stockStatus")),
      stockQuantity: Number(form.get("stockQuantity") || 0),
      premiumPercent,
      spreadPercent,
      liquidityScore,
      shippingSpeedScore,
      recommendationNotes: String(form.get("recommendationNotes") || "") || null,
      isIraEligible: form.get("isIraEligible") === "on",
      isFeatured: form.get("isFeatured") === "on",
      priceLastUpdatedAt: new Date(),
      lastPriceUpdatedAt: new Date(),
      seoTitle: String(form.get("seoTitle") || "") || null,
      seoDescription: String(form.get("seoDescription") || "") || null
    }
  });
  revalidatePath("/admin/products");
  revalidatePath("/");
  revalidatePath("/products");
  revalidatePath("/gold");
  revalidatePath("/silver");
  redirect("/admin/products");
}

export async function updateProduct(id: string, form: FormData) {
  const pricingMode = String(form.get("pricingMode") || "DIRECT_MANUAL");
  const manualPrice = Number(form.get("manualPrice") || 0);
  const supplierPrice = Number(form.get("supplierPrice") || 0);
  const markupPercent = Number(form.get("markupPercent") || 10);
  const customerPrice = pricingMode === "SUPPLIER_MARKUP" ? priceWithMarkup(supplierPrice, markupPercent) : manualPrice;
  const image = normalizeImagePath(form.get("image"));
  const itemKind = String(form.get("itemKind") || "PHYSICAL_BULLION");
  const premiumPercent = toNonNegativeNumber(form.get("premiumPercent"));
  const spreadPercent = toNonNegativeNumber(form.get("spreadPercent"));
  const liquidityScore = toBoundedScore(form.get("liquidityScore"));
  const shippingSpeedScore = toBoundedScore(form.get("shippingSpeedScore"));
  const existing = await prisma.product.findUnique({
    where: { id },
    select: { supplierPrice: true, markupPercent: true, customerPrice: true, totalSalePrice: true }
  });
  const priceChanged = existing
    ? Number(existing.supplierPrice) !== supplierPrice ||
      Number(existing.markupPercent) !== markupPercent ||
      Number(existing.customerPrice) !== customerPrice ||
      Number(existing.totalSalePrice) !== customerPrice
    : true;
  await prisma.product.update({
    where: { id },
    data: {
      name: String(form.get("name")),
      slug: String(form.get("slug")),
      metalType: String(form.get("metalType")),
      weight: String(form.get("weight")),
      purity: String(form.get("purity")),
      karat: String(form.get("karat") || "") || null,
      productType: String(form.get("productType")),
      itemKind,
      isPublicProduct: itemKind === "PHYSICAL_BULLION",
      isServiceItem: itemKind === "SERVICE",
      mintBrand: String(form.get("mintBrand")),
      brandMint: String(form.get("brandMint") || form.get("mintBrand")),
      supplierId: String(form.get("supplierId")),
      categoryId: String(form.get("categoryId") || "") || null,
      pricingMode,
      manualPrice,
      supplierPrice,
      markupPercent,
      customerPrice,
      totalSalePrice: customerPrice,
      shortDescription: String(form.get("shortDescription") || ""),
      description: String(form.get("description")),
      imageUrls: JSON.stringify([image]),
      images: JSON.stringify([image]),
      inventoryStatus: String(form.get("stockStatus")),
      stockStatus: String(form.get("stockStatus")),
      stockQuantity: Number(form.get("stockQuantity") || 0),
      premiumPercent,
      spreadPercent,
      liquidityScore,
      shippingSpeedScore,
      recommendationNotes: String(form.get("recommendationNotes") || "") || null,
      isIraEligible: form.get("isIraEligible") === "on",
      isFeatured: form.get("isFeatured") === "on",
      ...(priceChanged ? { priceLastUpdatedAt: new Date(), lastPriceUpdatedAt: new Date() } : {}),
      seoTitle: String(form.get("seoTitle") || "") || null,
      seoDescription: String(form.get("seoDescription") || "") || null
    }
  });
  revalidatePath("/admin/products");
  revalidatePath("/");
  revalidatePath("/products");
  revalidatePath("/gold");
  revalidatePath("/silver");
  revalidatePath(`/products/${String(form.get("slug"))}`);
  redirect("/admin/products");
}

export async function markPriceUpdated(id: string) {
  await prisma.product.update({ where: { id }, data: { priceLastUpdatedAt: new Date(), lastPriceUpdatedAt: new Date() } });
  revalidatePath("/admin/products");
  revalidatePath("/");
}

export async function deleteProduct(id: string) {
  await prisma.product.delete({ where: { id } });
  revalidatePath("/admin/products");
  revalidatePath("/");
}
