import { cache } from "react";
import { db } from "./db";

export type StoreSettings = {
  brandName: string;
  tagline: string;
  logoUrl: string; // full logo, transparent
  wordmarkUrl: string;
  monogramUrl: string;
  faviconUrl: string;
  email: string;
  phone: string;
  whatsapp: string; // digits incl. country code, e.g. 8801XXXXXXXXX
  address: string;
  social: { instagram?: string; facebook?: string; tiktok?: string };
  currency: "BDT";
  timezone: string;
  payments: {
    fullEnabled: boolean;
    depositEnabled: boolean;
    codEnabled: boolean;
    holdHours: number; // unpaid orders release stock / batch capacity after this
    bkash: { enabled: boolean; number: string; accountType: string };
    nagad: { enabled: boolean; number: string; accountType: string };
    bank: { enabled: boolean; details: string };
    gatewayTestMode: boolean;
  };
  preorder: { defaultTerms: string; splitShipmentAllowed: boolean };
  notifications: { orderPlaced: string; paymentVerified: string; shipped: string };
  analytics: { ga4Id: string; metaPixelId: string };
  announcement: { enabled: boolean; text: string; href: string };
};

export const DEFAULT_SETTINGS: StoreSettings = {
  brandName: "Veloura",
  tagline: "Your Style, Our Priority",
  logoUrl: "/brand/logo-full.png",
  wordmarkUrl: "/brand/wordmark.png",
  monogramUrl: "/brand/monogram.png",
  faviconUrl: "/icon.png",
  email: "hello@example.com",
  phone: "+880 1XXX-XXXXXX",
  whatsapp: "",
  address: "Dhaka, Bangladesh",
  social: { instagram: "", facebook: "", tiktok: "" },
  currency: "BDT",
  timezone: "Asia/Dhaka",
  payments: {
    fullEnabled: true,
    depositEnabled: true,
    codEnabled: true,
    holdHours: 24,
    bkash: { enabled: true, number: "01XXXXXXXXX", accountType: "Personal" },
    nagad: { enabled: true, number: "01XXXXXXXXX", accountType: "Personal" },
    bank: { enabled: false, details: "Bank name, account name, account number, branch, routing number" },
    gatewayTestMode: true,
  },
  preorder: {
    defaultTerms:
      "Pre-order items are made or sourced in batches after the batch closes. Dispatch dates are estimates and can move; we will message you if your batch is delayed. You can cancel for a full refund until the batch closes. After the batch closes, deposits are refundable only if we cannot fulfil your order or the dispatch window slips by more than 21 days.",
    splitShipmentAllowed: true,
  },
  notifications: {
    orderPlaced: "Hi {name}, we have received order {number}. Pay {dueNow} to secure it.",
    paymentVerified: "Hi {name}, we have verified your payment of {amount} for order {number}.",
    shipped: "Hi {name}, order {number} is on its way with {courier}. Tracking: {tracking}.",
  },
  analytics: { ga4Id: "", metaPixelId: "" },
  announcement: { enabled: true, text: "Pre-orders for the winter batch are open", href: "/pre-order-guide" },
};

function deepMerge<T>(base: T, over: unknown): T {
  if (!over || typeof over !== "object" || Array.isArray(over)) return base;
  const out: Record<string, unknown> = { ...(base as Record<string, unknown>) };
  for (const [k, v] of Object.entries(over as Record<string, unknown>)) {
    const b = (base as Record<string, unknown>)[k];
    out[k] = b && typeof b === "object" && !Array.isArray(b) ? deepMerge(b, v) : v;
  }
  return out as T;
}

export const getSettings = cache(async (): Promise<StoreSettings> => {
  try {
    const row = await db.setting.findUnique({ where: { key: "store" } });
    return deepMerge(DEFAULT_SETTINGS, row?.value);
  } catch {
    return DEFAULT_SETTINGS;
  }
});

export async function saveSettings(value: StoreSettings) {
  await db.setting.upsert({ where: { key: "store" }, create: { key: "store", value }, update: { value } });
}
