import { createHmac } from "crypto";
import { getMetaConfig, getMetaGraphBase } from "@/lib/env";

/** HMAC-SHA256 of access token keyed with app secret — required for server-side Graph API calls. */
export function buildAppSecretProof(accessToken: string, appSecret: string): string {
  return createHmac("sha256", appSecret).update(accessToken).digest("hex");
}

export function withMetaAccessToken(accessToken: string): URLSearchParams {
  const { appSecret } = getMetaConfig();
  const params = new URLSearchParams({ access_token: accessToken });
  if (appSecret) {
    params.set("appsecret_proof", buildAppSecretProof(accessToken, appSecret));
  }
  return params;
}

export function metaGraphGetUrl(
  path: string,
  accessToken: string,
  extra?: Record<string, string>,
): string {
  const params = withMetaAccessToken(accessToken);
  if (extra) {
    for (const [key, value] of Object.entries(extra)) {
      params.set(key, value);
    }
  }
  const normalized = path.startsWith("/") ? path : `/${path}`;
  return `${getMetaGraphBase()}${normalized}?${params.toString()}`;
}

export function withMetaAccessTokenBody(
  accessToken: string,
  fields: Record<string, string>,
): Record<string, string> {
  const { appSecret } = getMetaConfig();
  const body: Record<string, string> = { ...fields, access_token: accessToken };
  if (appSecret) {
    body.appsecret_proof = buildAppSecretProof(accessToken, appSecret);
  }
  return body;
}
