import "server-only";

import { createHmac, timingSafeEqual } from "crypto";

// Shopier Developer Portal > App > Webhooks bölümünden alınan token.
const WEBHOOK_TOKEN = process.env.SHOPIER_WEBHOOK_TOKEN ?? "";

// Her plan için Shopier mağazasındaki ürün URL'i.
const PLAN_URLS: Record<string, string> = {
  pro: process.env.SHOPIER_STORE_PRO_URL ?? "",
};

export function isShopierEnabled(): boolean {
  return (
    process.env.PAYMENT_PROVIDER === "shopier" &&
    Boolean(WEBHOOK_TOKEN) &&
    Boolean(PLAN_URLS.pro)
  );
}

export function getShopierPlanUrl(plan: string): string {
  return PLAN_URLS[plan] ?? "";
}

// Shopier HS256 imzasını doğrular.
// İmza formatı: HMAC-SHA256(webhook_token, raw_body) → base64
// Eğer ilk gerçek webhook'ta uyuşmazlık olursa hex formatını deneyin:
//   .digest("hex") yerine .digest("base64")
export function verifyShopierWebhookSignature(signature: string, rawBody: string): boolean {
  if (!WEBHOOK_TOKEN) return false;
  const expected = createHmac("sha256", WEBHOOK_TOKEN).update(rawBody).digest("base64");
  try {
    return timingSafeEqual(Buffer.from(expected), Buffer.from(signature));
  } catch {
    return false;
  }
}

// order.created webhook payload (Shopier Order modeli alt kümesi)
export type ShopierWebhookOrder = {
  id: string;
  status: string; // "fulfilled" | "unfulfilled"
  paymentStatus: string; // "paid" | "unpaid"
  dateCreated: string;
  currency: string;
  totals: {
    total: string;
    subtotal: string;
    discount: string;
    shipping: string;
  };
  shippingInfo: {
    email: string;
    firstName: string;
    lastName: string;
    phone?: string;
    company?: string;
  };
};
