import { prisma } from "@/lib/prisma";

export type ShippingSettingsData = {
  ratePerKgPaise: number;
  freeShippingThreshold: number;
  defaultItemWeightGrams: number;
  weightSlabGrams: number;
  minBillableWeightGrams: number;
};

export const SHIPPING_DEFAULTS: ShippingSettingsData = {
  ratePerKgPaise: 4800, // ₹48/kg
  freeShippingThreshold: 199900, // ₹1999
  defaultItemWeightGrams: 150,
  weightSlabGrams: 500,
  minBillableWeightGrams: 500,
};

/** Combines the default shipping method's rate with the global calculation settings — the one place checkout and the admin preview both read from. */
export async function getShippingSettings(): Promise<ShippingSettingsData> {
  const [settingsRow, defaultMethod] = await Promise.all([
    prisma.shippingSettings.findFirst(),
    prisma.shippingMethod.findFirst({ where: { isDefault: true, active: true } }),
  ]);

  return {
    ratePerKgPaise: defaultMethod?.ratePerKgPaise ?? SHIPPING_DEFAULTS.ratePerKgPaise,
    freeShippingThreshold: settingsRow?.freeShippingThreshold ?? SHIPPING_DEFAULTS.freeShippingThreshold,
    defaultItemWeightGrams: settingsRow?.defaultItemWeightGrams ?? SHIPPING_DEFAULTS.defaultItemWeightGrams,
    weightSlabGrams: settingsRow?.weightSlabGrams ?? SHIPPING_DEFAULTS.weightSlabGrams,
    minBillableWeightGrams: settingsRow?.minBillableWeightGrams ?? SHIPPING_DEFAULTS.minBillableWeightGrams,
  };
}

export function calculateShippingFee(subtotal: number, totalWeightGrams: number, settings: ShippingSettingsData) {
  if (subtotal >= settings.freeShippingThreshold) return 0;
  const billableGrams = Math.max(
    settings.minBillableWeightGrams,
    Math.ceil(totalWeightGrams / settings.weightSlabGrams) * settings.weightSlabGrams
  );
  return Math.round((billableGrams / 1000) * settings.ratePerKgPaise);
}
