import { rewardValue } from "@/lib/features/promo-codes/rewards";
import BreadCrumbLink from "@/layouts/shared/page.breadcrumbLink";
import { redirect } from "react-router";
import { createRoleProtectedLoader } from "@/lib/features/protectedFetcher";
import { getPromoCodeByCode } from "@/lib/features/promo-codes/query";
import { FEATURE_SLUGS } from "@/lib/role-helpers";

/**
 * Points a member receives from this promo code.
 *
 * Delegates to the shared reward reader — the inline version matched only the
 * exact string "POINTS", so a reward stored as "point" resolved to null.
 */
function extractPointsFromPromo(promo: unknown): number | null {
  return rewardValue(promo as Parameters<typeof rewardValue>[0], "points");
}

export const handle = {
  breadcrumb: ({
    params,
  }: {
    params: {
      campaignId: string;
      promoCodeId: string;
      membershipNumber: string;
    };
  }) => (
    <BreadCrumbLink
      links={[
        { label: "Promo Codes" },
        { label: "Campaigns", to: "/admin/promo-code-campaigns" },
        {
          label: "Promo Code",
          to: `/admin/promo-code-campaigns/${params.campaignId}/promo-codes/${params.promoCodeId}`,
        },
        { label: `Member #${params.membershipNumber}` },
      ]}
    />
  ),
};

export const loader = createRoleProtectedLoader(
  FEATURE_SLUGS.promoCodeCampaigns,
  "read",
  async ({ request, params }) => {
    const { campaignId, promoCodeId, membershipNumber } = params as {
      campaignId: string;
      promoCodeId: string;
      membershipNumber: string;
    };

    /*
     * Hand off to the member module rather than rendering a second copy of it.
     *
     * This page used to embed MemberClientPage with its own loader, which meant
     * every member feature had to be wired twice — and the copy drifted: it had
     * no overview strip, no session/log tabs, and its own booking fetch. The
     * member page owns all of that, so send the user there and carry the promo
     * context in the query string: `from` for the back link, `points` for the
     * reward this code allocated, which only the promo side knows.
     */
    const cookie = { Cookie: request.headers.get("Cookie") ?? "" };
    const promoResponse = await getPromoCodeByCode(promoCodeId, cookie);
    const pointsAllocated = promoResponse?.success
      ? extractPointsFromPromo(promoResponse.data)
      : null;

    const from = new URL(request.url).searchParams.get("from");
    const target = new URLSearchParams();
    target.set(
      "from",
      `/admin/promo-code-campaigns/${campaignId}/promo-codes/${promoCodeId}${
        from ? `?from=${encodeURIComponent(from)}` : ""
      }`,
    );
    target.set("fromLabel", promoCodeId);
    if (pointsAllocated !== null && pointsAllocated !== undefined) {
      target.set("points", String(pointsAllocated));
    }

    throw redirect(`/admin/members/${membershipNumber}?${target.toString()}`);
  },
);

// The loader always redirects; nothing renders here.
export default function Page() {
  return null;
}
