import { ExecArgs } from "@medusajs/framework/types";
import { ContainerRegistrationKeys } from "@medusajs/framework/utils";
import { updateShippingOptionsWorkflow } from "@medusajs/medusa/core-flows";

const TARGET_CODES = new Set(["standard", "express", "mondial-relay"]);
const TARGET_AMOUNT = 1000;

export default async function fixShippingPrices({ container }: ExecArgs) {
  const logger = container.resolve(ContainerRegistrationKeys.LOGGER);
  const query = container.resolve(ContainerRegistrationKeys.QUERY);

  const { data: regions } = await query.graph({
    entity: "region",
    fields: ["id", "currency_code"],
  });

  const eurRegion = (regions || []).find(
    (region: { currency_code?: string }) => region.currency_code === "eur"
  ) as { id: string } | undefined;

  if (!eurRegion?.id) {
    throw new Error("No EUR region found.");
  }

  const { data: shippingOptions } = await query.graph({
    entity: "shipping_option",
    fields: ["id", "name", "type.code"],
  });

  const candidates = (shippingOptions || []).filter((option: Record<string, unknown>) => {
    const code =
      ((option.type as { code?: string } | undefined)?.code || "").toLowerCase();
    if (TARGET_CODES.has(code)) {
      return true;
    }

    const name = String(option.name || "").toLowerCase();
    return (
      name.includes("standard shipping") ||
      name.includes("express shipping") ||
      name.includes("mondial relay")
    );
  });

  if (!candidates.length) {
    logger.info("No target shipping options found.");
    return;
  }

  const input = candidates.map((option: Record<string, unknown>) => ({
    id: String(option.id),
    prices: [
      { currency_code: "eur", amount: TARGET_AMOUNT },
      { currency_code: "usd", amount: TARGET_AMOUNT },
      { region_id: eurRegion.id, amount: TARGET_AMOUNT },
    ],
  }));

  await updateShippingOptionsWorkflow(container).run({ input });

  logger.info(
    `Updated ${input.length} shipping option(s) to ${TARGET_AMOUNT} (10,00 in minor units).`
  );
}

