import { HttpTypes } from "@medusajs/types";
import { InvoiceSettingsContent } from "@/lib/sanity/queries";

function asString(value: unknown) {
  return typeof value === "string" ? value.trim() : "";
}

function getOrderSuffix(order: HttpTypes.StoreOrder) {
  const display = order.display_id;
  if (typeof display === "number" || typeof display === "string") {
    const normalized = String(display).trim();
    if (normalized) {
      return normalized;
    }
  }

  const id = asString(order.id);
  return id ? id.slice(-8) : "order";
}

function applyTemplate(template: string, date: Date) {
  const year = String(date.getFullYear());
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const monthName = new Intl.DateTimeFormat("fr-FR", { month: "long" }).format(date).toUpperCase();

  return template
    .replaceAll("{YYYY}", year)
    .replaceAll("{YY}", year.slice(-2))
    .replaceAll("{MM}", month)
    .replaceAll("{MONTH}", monthName);
}

export function buildInvoiceNumber(order: HttpTypes.StoreOrder, settings: InvoiceSettingsContent | null) {
  const suffix = getOrderSuffix(order);
  const rawTemplate = asString(settings?.invoiceNumberPrefixTemplate);

  if (!rawTemplate) {
    return suffix;
  }

  const sourceDate = order.created_at ? new Date(order.created_at) : new Date();
  const date = Number.isNaN(sourceDate.getTime()) ? new Date() : sourceDate;
  const prefix = applyTemplate(rawTemplate, date).trim();

  if (!prefix) {
    return suffix;
  }

  return `${prefix}-${suffix}`;
}

