package com.rugvedsarika.easymath.data.repository

import com.rugvedsarika.easymath.data.db.MathDao
import com.rugvedsarika.easymath.data.db.MathHistoryEntity
import com.rugvedsarika.easymath.data.db.UserEntity
import com.rugvedsarika.easymath.data.db.AchievementEntity
import kotlinx.coroutines.flow.Flow

class MathRepository(private val mathDao: MathDao) {
    
    // User Operations
    val allUsers: Flow<List<UserEntity>> = mathDao.getAllUsers()
    
    suspend fun insertUser(user: UserEntity) {
        mathDao.insertUser(user)
    }

    suspend fun getUserById(userId: Int): UserEntity? {
        return mathDao.getUserById(userId)
    }

    suspend fun getUserCount(): Int {
        return mathDao.getUserCount()
    }

    // History Operations
    fun getAllHistory(userId: Int): Flow<List<MathHistoryEntity>> {
        return mathDao.getAllHistory(userId)
    }

    fun getTopScores(category: String, userId: Int): Flow<List<MathHistoryEntity>> {
        return mathDao.getTopScores(category, userId)
    }

    fun getOverallAccuracy(userId: Int): Flow<Float?> {
        return mathDao.getOverallAccuracy(userId)
    }

    suspend fun insertHistory(history: MathHistoryEntity) {
        mathDao.insertHistory(history)
    }

    suspend fun clearHistory() {
        mathDao.clearHistory()
    }

    // Achievements
    val achievements: Flow<List<AchievementEntity>> = mathDao.getAchievements(1) // Default user, needs dynamic update

    fun getAchievements(userId: Int): Flow<List<AchievementEntity>> = mathDao.getAchievements(userId)

    suspend fun unlockAchievement(userId: Int, code: String) {
        mathDao.unlockAchievement(userId, code, System.currentTimeMillis())
    }
    
    suspend fun getGamesPlayedCount(userId: Int): Int = mathDao.getGamesPlayedCount(userId)
    
    suspend fun getTotalScore(userId: Int): Int = mathDao.getTotalScore(userId) ?: 0
    
    suspend fun insertAchievement(achievement: AchievementEntity) = mathDao.insertAchievement(achievement)
}
