import { config } from '../config';

/** Decode referer segment from /customer/login/referer/<b64>/… */
export function refererPathFromAjxSubPath(subPath: string): string | null {
  const match = subPath.match(/\/referer\/([^/]+)/);
  if (!match) return null;
  try {
    let decoded = Buffer.from(match[1], 'base64').toString('utf8').trim();
    decoded = decoded.replace(/,+$/, '');
    if (!decoded) return null;
    if (/^https?:\/\//i.test(decoded)) {
      return new URL(decoded).pathname || null;
    }
    return decoded.startsWith('/') ? decoded : `/${decoded}`;
  } catch {
    return null;
  }
}

function checkoutTargetPath(refererPath: string): string | null {
  if (refererPath.includes('/checkout/order')) {
    return config.intercept.checkoutOrderPath;
  }
  if (refererPath.includes('/checkout/cart')) {
    return config.intercept.cartPagePath;
  }
  if (refererPath.includes('/checkout')) {
    return config.intercept.checkoutOrderPath;
  }
  return null;
}

/** After login/register, keep user on mirror checkout (not upstream homepage). */
export function rewriteCustomerAuthResponse(
  body: Buffer,
  ajxSubPath: string,
  mirrorOrigin: string,
): Buffer {
  if (!/\/customer\/(login|register)\b/.test(ajxSubPath)) {
    return body;
  }

  let data: Record<string, unknown>;
  try {
    data = JSON.parse(body.toString('utf8')) as Record<string, unknown>;
  } catch {
    return body;
  }

  if (!data.status) return body;

  const refererPath = refererPathFromAjxSubPath(ajxSubPath);
  if (!refererPath) return body;

  const targetPath = checkoutTargetPath(refererPath);
  if (!targetPath) return body;

  const origin = mirrorOrigin.replace(/\/$/, '');
  const path =
    targetPath.endsWith('/') || targetPath.includes('?')
      ? targetPath
      : `${targetPath}/`;
  const url = `${origin}${path}`;

  const content =
    data.content && typeof data.content === 'object'
      ? (data.content as Record<string, unknown>)
      : {};
  content.url = url;
  data.content = content;

  return Buffer.from(JSON.stringify(data), 'utf8');
}

export function frontendIdFromSetCookie(
  headers: Record<string, string | string[] | undefined>,
): string | undefined {
  const raw = headers['set-cookie'];
  const list = Array.isArray(raw) ? raw : raw ? [String(raw)] : [];
  for (const line of list) {
    const match = /^frontend=([^;]+)/i.exec(line.trim());
    if (match) return match[1];
  }
  return undefined;
}
