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 here 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: { code: string; membershipNumber: string };
  }) => (
    <BreadCrumbLink
      links={[
        { label: "Promo Codes", to: "/admin/promo-codes" },
        {
          label: "Promo Code",
          to: `/admin/promo-codes/${params.code}`,
        },
        { label: `Member #${params.membershipNumber}` },
      ]}
    />
  ),
};

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

    // Hand off to the member module rather than embedding a second copy of it —
    // see the campaign drilldown for the reasoning. `points` is the one thing
    // only the promo side knows.
    const cookie = { Cookie: request.headers.get("Cookie") ?? "" };
    const promoResponse = await getPromoCodeByCode(code, cookie);
    const pointsAllocated = promoResponse?.success
      ? extractPointsFromPromo(promoResponse.data)
      : null;

    const target = new URLSearchParams();
    target.set("from", `/admin/promo-codes/${code}`);
    target.set("fromLabel", code);
    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;
}
