package com.rugvedsarika.easymath.utils

import com.rugvedsarika.easymath.data.db.AchievementEntity
import com.rugvedsarika.easymath.data.repository.MathRepository

object AchievementManager {

    val ALL_ACHIEVEMENTS = listOf(
        AchievementEntity(
            userId = 0, // Placeholder
            code = "FIRST_STEPS",
            name = "First Steps",
            description = "Complete your first game.",
            iconResId = android.R.drawable.ic_menu_compass
        ),
        AchievementEntity(
            userId = 0,
            code = "SHARPSHOOTER",
            name = "Sharpshooter",
            description = "Get 100% accuracy in a game with > 5 questions.",
            iconResId = android.R.drawable.ic_menu_mylocation
        ),
        AchievementEntity(
            userId = 0,
            code = "SPEED_DEMON",
            name = "Speed Demon",
            description = "Score > 10 in Speed Challenge.",
            iconResId = android.R.drawable.ic_menu_recent_history
        ),
        AchievementEntity(
            userId = 0,
            code = "MATH_WIZARD",
            name = "Math Wizard",
            description = "Get a total score of 100.",
            iconResId = android.R.drawable.star_big_on
        )
    )

    suspend fun checkAchievements(repository: MathRepository, userId: Int) {
        val history = repository.getGamesPlayedCount(userId)
        val totalScore = repository.getTotalScore(userId)
        
        // 1. First Steps
        if (history >= 1) {
            unlock(repository, userId, "FIRST_STEPS")
        }
        
        // 4. Math Wizard
        if (totalScore >= 100) {
            unlock(repository, userId, "MATH_WIZARD")
        }
    }
    
    suspend fun checkGameAchievements(repository: MathRepository, userId: Int, score: Int, total: Int, category: String) {
        // 2. Sharpshooter
        if (total > 5 && score == total) {
             unlock(repository, userId, "SHARPSHOOTER")
        }
        
        // 3. Speed Demon
        if (category == "Speed_Challenge" && score > 10) {
            unlock(repository, userId, "SPEED_DEMON")
        }
    }
    
    private suspend fun unlock(repository: MathRepository, userId: Int, code: String) {
        // In a real app, we check if already unlocked to avoid re-toast
        // For now, Repo/DAO query updates timestamp if exists, or inserts.
        // But we need to INSERT safely if not exists.
        // Actually Dao has onConflict = REPLACE, but we don't want to reset timestamp if already unlocked?
        // Let's use the specific unlockQuery which sets unlocked=1. 
        // BUT we need to ensure the row exists first.
        // Strategy: We should pre-populate achievements when user is created.
        
        repository.unlockAchievement(userId, code)
    }
}
