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

const VOTE_HASH_KEY = "dbsync:votes"
const COMMENT_LIKE_HASH_KEY = "dbsync:commentLikes"
const COMMENT_HASH_KEY = "dbsync:comments"
const COMMENT_DELETE_HASH_KEY = "dbsync:commentDeletes"
const DEAL_UPDATE_HASH_KEY = "dbsync:dealUpdates"
const DEAL_CREATE_HASH_KEY = "dbsync:dealCreates"
const DEAL_AI_REVIEW_HASH_KEY = "dbsync:dealAiReviews"
const NOTIFICATION_HASH_KEY = "dbsync:notifications"
const NOTIFICATION_READ_HASH_KEY = "dbsync:notificationReads"
const DEAL_SAVE_HASH_KEY = "dbsync:dealSaves"
const AUDIT_HASH_KEY = "dbsync:audits"
const USER_UPDATE_HASH_KEY = "dbsync:users"
const USER_NOTE_HASH_KEY = "dbsync:userNotes"
const DEAL_REPORT_UPDATE_HASH_KEY = "dbsync:dealReportUpdates"
const CATEGORY_UPSERT_HASH_KEY = "dbsync:categoryUpserts"
const SELLER_UPSERT_HASH_KEY = "dbsync:sellerUpserts"
const SELLER_DOMAIN_UPSERT_HASH_KEY = "dbsync:sellerDomainUpserts"

function createRedisClient() {
  return getRedisClient()
}

async function queueVoteUpdate({ dealId, userId, voteType, createdAt }) {
  if (!dealId || !userId) return
  const redis = createRedisClient()

  try {
    const field = `vote:${dealId}:${userId}`
    const payload = JSON.stringify({
      dealId: Number(dealId),
      userId: Number(userId),
      voteType: Number(voteType),
      createdAt,
    })
    await redis.hset(VOTE_HASH_KEY, field, payload)
  } finally {}
}

async function queueCommentLikeUpdate({ commentId, userId, like, createdAt }) {
  if (!commentId || !userId) return
  const redis = createRedisClient()

  try {
    const field = `commentLike:${commentId}:${userId}`
    const payload = JSON.stringify({
      commentId: Number(commentId),
      userId: Number(userId),
      like: Boolean(like),
      createdAt,
    })
    await redis.hset(COMMENT_LIKE_HASH_KEY, field, payload)
  } finally {}
}

async function queueCommentCreate({ commentId, dealId, userId, text, parentId, createdAt }) {
  if (!commentId || !dealId || !userId) return
  const redis = createRedisClient()

  try {
    const field = `comment:${commentId}`
    const payload = JSON.stringify({
      commentId: Number(commentId),
      dealId: Number(dealId),
      userId: Number(userId),
      text: String(text || ""),
      parentId: parentId ? Number(parentId) : null,
      createdAt,
    })
    await redis.hset(COMMENT_HASH_KEY, field, payload)
  } finally {}
}

async function queueCommentDelete({ commentId, dealId, createdAt }) {
  if (!commentId || !dealId) return
  const redis = createRedisClient()

  try {
    const field = `commentDelete:${commentId}`
    const payload = JSON.stringify({
      commentId: Number(commentId),
      dealId: Number(dealId),
      createdAt,
    })
    await redis.hset(COMMENT_DELETE_HASH_KEY, field, payload)
  } finally {}
}

async function queueDealUpdate({ dealId, data, updatedAt }) {
  if (!dealId || !data || typeof data !== "object") return
  const redis = createRedisClient()

  try {
    const field = `dealUpdate:${dealId}`
    const payload = JSON.stringify({
      dealId: Number(dealId),
      data,
      updatedAt,
    })
    await redis.hset(DEAL_UPDATE_HASH_KEY, field, payload)
  } finally {}
}

async function queueDealCreate({ dealId, data, images = [], createdAt }) {
  if (!dealId || !data || typeof data !== "object") return
  const redis = createRedisClient()

  try {
    const field = `dealCreate:${dealId}`
    const payload = JSON.stringify({
      dealId: Number(dealId),
      data,
      images: Array.isArray(images) ? images : [],
      createdAt,
    })
    await redis.hset(DEAL_CREATE_HASH_KEY, field, payload)
  } finally {}
}

async function queueDealAiReviewUpdate({ dealId, data, updatedAt }) {
  if (!dealId || !data || typeof data !== "object") return
  const redis = createRedisClient()

  try {
    const field = `dealAiReview:${dealId}`
    const payload = JSON.stringify({
      dealId: Number(dealId),
      data,
      updatedAt,
    })
    await redis.hset(DEAL_AI_REVIEW_HASH_KEY, field, payload)
  } finally {}
}

async function queueNotificationCreate({ userId, message, type = "INFO", createdAt }) {
  if (!userId || !message) return
  const redis = createRedisClient()

  try {
    const field = `notification:${userId}:${Date.now()}`
    const payload = JSON.stringify({
      userId: Number(userId),
      message: String(message),
      type: String(type || "INFO"),
      createdAt,
    })
    await redis.hset(NOTIFICATION_HASH_KEY, field, payload)
  } finally {}
}

async function queueNotificationReadAll({ userId, readAt }) {
  if (!userId) return
  const redis = createRedisClient()

  try {
    const field = `notificationRead:${userId}:${Date.now()}`
    const payload = JSON.stringify({
      userId: Number(userId),
      readAt,
    })
    await redis.hset(NOTIFICATION_READ_HASH_KEY, field, payload)
  } finally {}
}

async function queueDealSaveUpdate({ dealId, userId, action, createdAt }) {
  if (!dealId || !userId) return
  const normalized = String(action || "").toUpperCase()
  if (!["SAVE", "UNSAVE"].includes(normalized)) return
  const redis = createRedisClient()

  try {
    const field = `dealSave:${dealId}:${userId}`
    const payload = JSON.stringify({
      dealId: Number(dealId),
      userId: Number(userId),
      action: normalized,
      createdAt,
    })
    await redis.hset(DEAL_SAVE_HASH_KEY, field, payload)
  } finally {}
}

async function queueAuditEvent({ userId, action, ip, userAgent, meta = null, createdAt }) {
  if (!action) return
  const redis = createRedisClient()
  try {
    const field = `audit:${Date.now()}:${Math.random().toString(36).slice(2, 8)}`
    const payload = JSON.stringify({
      userId: userId ? Number(userId) : null,
      action: String(action),
      ip: ip ?? null,
      userAgent: userAgent ?? null,
      meta,
      createdAt,
    })
    await redis.hset(AUDIT_HASH_KEY, field, payload)
  } finally {}
}

async function queueUserUpdate({ userId, data, updatedAt }) {
  if (!userId || !data || typeof data !== "object") return
  const redis = createRedisClient()
  try {
    const field = `userUpdate:${userId}`
    const payload = JSON.stringify({
      userId: Number(userId),
      data,
      updatedAt,
    })
    await redis.hset(USER_UPDATE_HASH_KEY, field, payload)
  } finally {}
}

async function queueUserNoteCreate({ userId, createdById, note, createdAt }) {
  if (!userId || !createdById || !note) return
  const redis = createRedisClient()
  try {
    const field = `userNote:${userId}:${Date.now()}`
    const payload = JSON.stringify({
      userId: Number(userId),
      createdById: Number(createdById),
      note: String(note),
      createdAt,
    })
    await redis.hset(USER_NOTE_HASH_KEY, field, payload)
  } finally {}
}

async function queueDealReportStatusUpdate({ reportId, status, updatedAt }) {
  if (!reportId || !status) return
  const redis = createRedisClient()
  try {
    const field = `dealReport:${reportId}`
    const payload = JSON.stringify({
      reportId: Number(reportId),
      status: String(status),
      updatedAt,
    })
    await redis.hset(DEAL_REPORT_UPDATE_HASH_KEY, field, payload)
  } finally {}
}

async function queueCategoryUpsert({ categoryId, data, updatedAt }) {
  if (!categoryId || !data || typeof data !== "object") return
  const redis = createRedisClient()
  try {
    const field = `category:${categoryId}`
    const payload = JSON.stringify({
      categoryId: Number(categoryId),
      data,
      updatedAt,
    })
    await redis.hset(CATEGORY_UPSERT_HASH_KEY, field, payload)
  } finally {}
}

async function queueSellerUpsert({ sellerId, data, updatedAt }) {
  if (!sellerId || !data || typeof data !== "object") return
  const redis = createRedisClient()
  try {
    const field = `seller:${sellerId}`
    const payload = JSON.stringify({
      sellerId: Number(sellerId),
      data,
      updatedAt,
    })
    await redis.hset(SELLER_UPSERT_HASH_KEY, field, payload)
  } finally {}
}

async function queueSellerDomainUpsert({ sellerId, domain, createdById }) {
  if (!sellerId || !domain || !createdById) return
  const redis = createRedisClient()
  try {
    const field = `sellerDomain:${sellerId}:${String(domain).toLowerCase()}`
    const payload = JSON.stringify({
      sellerId: Number(sellerId),
      domain: String(domain).toLowerCase(),
      createdById: Number(createdById),
    })
    await redis.hset(SELLER_DOMAIN_UPSERT_HASH_KEY, field, payload)
  } finally {}
}

module.exports = {
  queueVoteUpdate,
  queueCommentLikeUpdate,
  queueCommentCreate,
  queueCommentDelete,
  queueDealUpdate,
  queueDealCreate,
  queueDealAiReviewUpdate,
  queueNotificationCreate,
  queueNotificationReadAll,
  queueDealSaveUpdate,
  queueAuditEvent,
  queueUserUpdate,
  queueUserNoteCreate,
  queueDealReportStatusUpdate,
  queueCategoryUpsert,
  queueSellerUpsert,
  queueSellerDomainUpsert,
  COMMENT_HASH_KEY,
  COMMENT_DELETE_HASH_KEY,
  VOTE_HASH_KEY,
  COMMENT_LIKE_HASH_KEY,
  DEAL_UPDATE_HASH_KEY,
  DEAL_CREATE_HASH_KEY,
  DEAL_AI_REVIEW_HASH_KEY,
  NOTIFICATION_HASH_KEY,
  NOTIFICATION_READ_HASH_KEY,
  DEAL_SAVE_HASH_KEY,
  AUDIT_HASH_KEY,
  USER_UPDATE_HASH_KEY,
  USER_NOTE_HASH_KEY,
  DEAL_REPORT_UPDATE_HASH_KEY,
  CATEGORY_UPSERT_HASH_KEY,
  SELLER_UPSERT_HASH_KEY,
  SELLER_DOMAIN_UPSERT_HASH_KEY,
}
