import { MedusaContainer } from "@medusajs/framework"
import {
  ContainerRegistrationKeys,
  ModuleRegistrationName,
} from "@medusajs/framework/utils"
import { updateStoresWorkflow } from "@medusajs/medusa/core-flows"

export default async function seed_indonesia_store({
  container,
}: {
  container: MedusaContainer
}) {
  const logger = container.resolve(ContainerRegistrationKeys.LOGGER)
  const query = container.resolve(ContainerRegistrationKeys.QUERY)

  // =====================
  // 1. Query existing data
  // =====================
  logger.info("Querying existing data...")

  const { data: stores } = await query.graph({
    entity: "store",
    fields: ["id", "name"],
  })
  const store = stores?.[0]
  if (!store) {
    logger.error("No store found. Aborting.")
    return
  }
  logger.info(`Store: ${store.name} (${store.id})`)

  const { data: variants } = await query.graph({
    entity: "product_variant",
    fields: ["id", "title", "sku", "product_id"],
  })

  // =====================
  // 2. Update store currencies to IDR only
  // =====================
  logger.info("Updating store currencies to IDR...")
  await updateStoresWorkflow(container).run({
    input: {
      selector: { id: store.id },
      update: {
        supported_currencies: [
          { currency_code: "idr", is_default: true },
          { currency_code: "eur", is_default: false },
          { currency_code: "usd", is_default: false },
        ],
      },
    },
  })
  logger.info("Store currencies updated to IDR only.")

  // =====================
  // 3. Add locale "id" to store
  // =====================
  logger.info("Adding locale 'id' to store...")
  await updateStoresWorkflow(container).run({
    input: {
      selector: { id: store.id },
      update: {
        supported_locales: [
          { locale_code: "id" },
        ],
      },
    },
  })
  logger.info("Locale 'id' added to store.")

  // =====================
  // 4. Add IDR prices to all product variants
  // =====================
  if (variants?.length) {
    logger.info(`Adding IDR prices to ${variants.length} variants...`)

    const productPrices: Record<string, number> = {
      "SHIRT": 175000,
      "SWEATSHIRT": 350000,
      "SWEATPANTS": 300000,
      "SHORTS": 200000,
    }

    const getAmount = (sku: string): number => {
      for (const [prefix, amount] of Object.entries(productPrices)) {
        if (sku.startsWith(prefix)) return amount
      }
      return 150000
    }

    const { data: variantPriceSets } = await query.graph({
      entity: "product_variant_price_set",
      fields: ["variant_id", "price_set_id"],
    })

    const pricingModuleService = container.resolve(
      ModuleRegistrationName.PRICING
    )

    const variantPriceSetMap = new Map(
      variantPriceSets?.map((vps: any) => [vps.variant_id, vps.price_set_id]) ?? []
    )

    const pricesToCreate = variants
      .filter((v: any) => variantPriceSetMap.has(v.id))
      .map((v: any) => ({
        price_set_id: variantPriceSetMap.get(v.id),
        currency_code: "idr",
        amount: getAmount(v.sku),
      }))

    if (pricesToCreate.length) {
      await (pricingModuleService as any).createPrices(pricesToCreate)
      logger.info(`IDR prices added to ${pricesToCreate.length} variants.`)
    } else {
      logger.info("No variant price set links found.")
    }
  } else {
    logger.info("No variants found. Skipping price addition.")
  }

  logger.info("Indonesia store seed completed.")
}
