import storeConfig from "discovery.config";

import { B2BAgentLayout } from "../features/b2b-agent/layouts";
import { withErrorBoundary } from "../features/shared/components";
import { LOCALIZATION_ENTRY_IDS } from "../features/shared/localization/constants";
import { LocalizationProvider } from "../features/shared/localization/LocalizationContext";
import { getLocalizationLabelsService } from "../features/shared/localization/services/get-localization-labels.service";
import {
  withAuthLoader,
  withLoaderErrorBoundary,
} from "../features/shared/utils";

import type { LabelMap } from "../features/shared/localization/types";
import type { AuthRouteProps, LoaderData } from "../features/shared/types";

/**
 * Extracts the VTEX auth token value from a Cookie header string.
 * Returns only the cookie VALUE (JWT), never "CookieName=value".
 */
const getAuthCookieInfo = (
  cookieHeader: string
): { token: string; accountFromCookie?: string } => {
  if (!cookieHeader) return { token: "" };

  // VtexIdclientAutCookie_<account>=<value>
  const m = cookieHeader.match(/VtexIdclientAutCookie_([a-zA-Z0-9-]+)=([^;]+)/);
  if (m?.[2]) return { accountFromCookie: m[1], token: m[2] };

  // fallback: VtexIdclientAutCookie=<value>
  const g = cookieHeader.match(/VtexIdclientAutCookie=([^;]+)/);
  if (g?.[1]) return { token: g[1] };

  return { token: "" };
};

type B2BAgentPageQuery = Record<string, never>;

type B2BAgentPageData = { localizationLabels: LabelMap };

const loaderFunction = async (
  data: LoaderData<B2BAgentPageQuery>
): Promise<AuthRouteProps<B2BAgentPageData>> => {
  return withAuthLoader(data, async () => {
    const localizationLabels = await getLocalizationLabelsService({
      entryIds: LOCALIZATION_ENTRY_IDS.b2bAgent,
      locale: data.locale,
    });

    return { localizationLabels };
  });
};

export const loader = withLoaderErrorBoundary(loaderFunction, {
  componentName: "B2BAgentPage",
  redirectToError: true,
});

const B2BAgentPage = (props: AuthRouteProps<B2BAgentPageData>) => {
  if (!props.authorized) return null;

  const cookieHeader = props.clientContext?.cookie ?? "";
  const tokenFromContext = props.clientContext?.vtexIdclientAutCookie ?? "";

  const { token: tokenFromCookie, accountFromCookie } =
    getAuthCookieInfo(cookieHeader);

  // Prefer a token-like value if available; otherwise extract from cookie header.
  const vtexIdclientAutCookie =
    tokenFromContext && !tokenFromContext.includes("=")
      ? tokenFromContext
      : tokenFromCookie;

  if (!vtexIdclientAutCookie) {
    throw new Error("Missing VTEX auth token for B2B Agent iframe");
  }

  // account/locale via discovery.config (recomendado)
  const account = storeConfig?.api?.storeId ?? accountFromCookie ?? "";
  const locale = storeConfig?.session?.locale ?? "en-US";

  const customerId = props.clientContext?.customerId;
  const userId = props.clientContext?.userId;

  return (
    <LocalizationProvider labels={props.data?.localizationLabels ?? {}}>
      <B2BAgentLayout
        vtexIdclientAutCookie={vtexIdclientAutCookie}
        account={account}
        locale={locale}
        customerId={customerId}
        userId={userId}
      />
    </LocalizationProvider>
  );
};

export default withErrorBoundary(B2BAgentPage, {
  onError: (error) => {
    console.error("onError", error);
  },
  tags: {
    component: "B2BAgentPage",
    errorType: "b2b_agent_error",
  },
});
