const { getRedisClient } = require("./client")

function createRedisClient() {
  return getRedisClient()
}

async function ensureDealSearchIndex() {
  const redis = createRedisClient()

  try {
    await redis.call(
      "FT.CREATE",
      "idx:data:deals",
      "ON",
      "JSON",
      "PREFIX",
      "1",
      "data:deals:",
      "SCHEMA",
      "$.id",
      "AS",
      "id",
      "NUMERIC",
      "SORTABLE",
      "$.title",
      "AS",
      "title",
      "TEXT",
      "WEIGHT",
      "5.0",
      "$.description",
      "AS",
      "description",
      "TEXT",
      "WEIGHT",
      "2.0",
      "$.url",
      "AS",
      "url",
      "TEXT",
      "$.price",
      "AS",
      "price",
      "NUMERIC",
      "SORTABLE",
      "$.originalPrice",
      "AS",
      "originalPrice",
      "NUMERIC",
      "$.shippingPrice",
      "AS",
      "shippingPrice",
      "NUMERIC",
      "$.percentOff",
      "AS",
      "percentOff",
      "NUMERIC",
      "$.couponCode",
      "AS",
      "couponCode",
      "TEXT",
      "$.location",
      "AS",
      "location",
      "TEXT",
      "$.discountType",
      "AS",
      "discountType",
      "TAG",
      "$.discountValue",
      "AS",
      "discountValue",
      "NUMERIC",
      "$.userId",
      "AS",
      "userId",
      "NUMERIC",
      "SORTABLE",
      "$.score",
      "AS",
      "score",
      "NUMERIC",
      "SORTABLE",
      "$.commentCount",
      "AS",
      "commentCount",
      "NUMERIC",
      "$.status",
      "AS",
      "status",
      "TAG",
      "$.saletype",
      "AS",
      "saletype",
      "TAG",
      "$.affiliateType",
      "AS",
      "affiliateType",
      "TAG",
      "$.sellerId",
      "AS",
      "sellerId",
      "NUMERIC",
      "$.customSeller",
      "AS",
      "customSeller",
      "TEXT",
      "$.categoryId",
      "AS",
      "categoryId",
      "NUMERIC",
      "SORTABLE",
      "$.createdAt",
      "AS",
      "createdAt",
      "TEXT",
      "$.createdAtTs",
      "AS",
      "createdAtTs",
      "NUMERIC",
      "SORTABLE",
      "$.updatedAt",
      "AS",
      "updatedAt",
      "TEXT",
      "$.updatedAtTs",
      "AS",
      "updatedAtTs",
      "NUMERIC",
      "SORTABLE",
      "$.seller.name",
      "AS",
      "sellerName",
      "TEXT",
      "$.seller.id",
      "AS",
      "sellerIdNested",
      "NUMERIC",
      "$.seller.url",
      "AS",
      "sellerUrl",
      "TEXT",
      "$.user.id",
      "AS",
      "userIdNested",
      "NUMERIC",
      "$.user.username",
      "AS",
      "username",
      "TEXT",
      "$.images[*].imageUrl",
      "AS",
      "imageUrls",
      "TEXT",
      "$.tags[*].slug",
      "AS",
      "tagSlugs",
      "TAG"
    )

    console.log("✅ Redis search index created: idx:data:deals")
    await ensureDealIndexFields(redis)
  } catch (err) {
    const message = err?.message || ""
    if (message.includes("Index already exists")) {
      console.log("ℹ️ Redis search index already exists: idx:data:deals")
      await ensureDealIndexFields(redis)
    } else {
      throw err
    }
  } finally {}
}

async function ensureDealIndexFields(redis) {
  const fields = [
    [
      "$.createdAtTs",
      "AS",
      "createdAtTs",
      "NUMERIC",
      "SORTABLE",
    ],
    [
      "$.updatedAtTs",
      "AS",
      "updatedAtTs",
      "NUMERIC",
      "SORTABLE",
    ],
    [
      "$.couponCode",
      "AS",
      "couponCode",
      "TEXT",
    ],
    [
      "$.hasCouponCode",
      "AS",
      "hasCouponCode",
      "NUMERIC",
      "SORTABLE",
    ],
  ]

  for (const field of fields) {
    try {
      await redis.call("FT.ALTER", "idx:data:deals", "SCHEMA", "ADD", ...field)
      console.log(`✅ Redis search index field added: ${field[2]}`)
    } catch (err) {
      const message = err?.message || ""
      if (!message.includes("Duplicate field")) {
        throw err
      }
    }
  }
}

module.exports = { ensureDealSearchIndex }
