// import redisClient from '@/src/lib/redis-client'
import {
  getAllUserNegativityScores as getAllUserNegativityScoresFromDb,
  getUserNegativityScore as getUserNegativityScoreFromDb,
  type UserNegativityData,
} from '@/src/dbService'

export async function initializeUserNegativityStore(): Promise<void> {
  try {
    console.log('Initializing user negativity store in Redis...')

    const results = await getAllUserNegativityScoresFromDb()

    /*
    // Old implementation - direct DB queries:
    import { db } from '@/src/db/db_index'
    import { userIncidents } from '@/src/db/schema'
    import { sum } from 'drizzle-orm'

    const results = await db
      .select({
        userId: userIncidents.userId,
        totalNegativityScore: sum(userIncidents.negativityScore).mapWith(Number),
      })
      .from(userIncidents)
      .groupBy(userIncidents.userId);
    */

    // for (const { userId, totalNegativityScore } of results) {
    //   await redisClient.set(
    //     `user:negativity:${userId}`,
    //     totalNegativityScore.toString()
    //   )
    // }

    console.log(`User negativity store initialized for ${results.length} users`)
  } catch (error) {
    console.error('Error initializing user negativity store:', error)
    throw error
  }
}

export async function getUserNegativity(userId: number): Promise<number> {
  try {
    // const key = `user:negativity:${userId}`
    // const data = await redisClient.get(key)
    //
    // if (!data) {
    //   return 0
    // }
    //
    // return parseInt(data, 10)

    return await getUserNegativityScoreFromDb(userId)
  } catch (error) {
    console.error(`Error getting negativity score for user ${userId}:`, error)
    return 0
  }
}

export async function getAllUserNegativityScores(): Promise<Record<number, number>> {
  try {
    // const keys = await redisClient.KEYS('user:negativity:*')
    //
    // if (keys.length === 0) return {}
    //
    // const values = await redisClient.MGET(keys)
    //
    // const result: Record<number, number> = {}
    // for (let i = 0; i < keys.length; i++) {
    //   const key = keys[i]
    //   const value = values[i]
    //
    //   const match = key.match(/user:negativity:(\d+)/)
    //   if (match && value) {
    //     const userId = parseInt(match[1], 10)
    //     result[userId] = parseInt(value, 10)
    //   }
    // }
    //
    // return result

    const results = await getAllUserNegativityScoresFromDb()

    const result: Record<number, number> = {}
    for (const { userId, totalNegativityScore } of results) {
      result[userId] = totalNegativityScore
    }
    return result
  } catch (error) {
    console.error('Error getting all user negativity scores:', error)
    return {}
  }
}

export async function getMultipleUserNegativityScores(
  userIds: number[]
): Promise<Record<number, number>> {
  try {
    if (userIds.length === 0) return {}

    // const keys = userIds.map((id) => `user:negativity:${id}`)
    //
    // const values = await redisClient.MGET(keys)
    //
    // const result: Record<number, number> = {}
    // for (let i = 0; i < userIds.length; i++) {
    //   const value = values[i]
    //   if (value) {
    //     result[userIds[i]] = parseInt(value, 10)
    //   } else {
    //     result[userIds[i]] = 0
    //   }
    // }
    //
    // return result

    const result: Record<number, number> = {}
    for (const userId of userIds) {
      result[userId] = await getUserNegativityScoreFromDb(userId)
    }
    return result
  } catch (error) {
    console.error('Error getting multiple user negativity scores:', error)
    return {}
  }
}

export async function recomputeUserNegativityScore(userId: number): Promise<void> {
  try {
    const totalScore = await getUserNegativityScoreFromDb(userId)

    /*
    // Old implementation - direct DB queries:
    import { db } from '@/src/db/db_index'
    import { userIncidents } from '@/src/db/schema'
    import { eq, sum } from 'drizzle-orm'

    const [result] = await db
      .select({
        totalNegativityScore: sum(userIncidents.negativityScore).mapWith(Number),
      })
      .from(userIncidents)
      .where(eq(userIncidents.userId, userId))
      .limit(1);

    const totalScore = result?.totalNegativityScore || 0;
    */

    // const key = `user:negativity:${userId}`
    // await redisClient.set(key, totalScore.toString())
  } catch (error) {
    console.error(`Error recomputing negativity score for user ${userId}:`, error)
    throw error
  }
}
