package com.example.match.repository

import android.content.Context
import com.example.match.db.AppDatabase
import com.example.match.db.PredictionEntity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

object PredictionRepository {

    suspend fun savePrediction(
        context: Context,
        prediction: PredictionEntity
    ): Result<Long> = withContext(Dispatchers.IO) {
        val dao = AppDatabase.getInstance(context).predictionDao()
        val rowId = dao.insertPrediction(prediction)
        if (rowId > 0) {
            // Success, return the generated rowId
            Result.success(rowId)
        } else {
            Result.failure(Exception("Failed to insert prediction."))
        }
    }

    suspend fun getPredictionForUserAndMatch(
        context: Context,
        matchId: String,
        userId: Int
    ): PredictionEntity? = withContext(Dispatchers.IO) {
        val dao = AppDatabase.getInstance(context).predictionDao()
        dao.getPredictionForUserAndMatch(matchId, userId)
    }

    suspend fun updatePredictionCorrect(
        context: Context,
        predictionId: Int,
        isCorrect: Boolean
    ): Boolean = withContext(Dispatchers.IO) {
        val db = AppDatabase.getInstance(context)
        val dao = db.predictionDao()

        // Find the existing entity by its primary key
        val pred = dao.findById(predictionId) ?: return@withContext false
        // Update with the new isCorrect value
        val updatedRows = dao.updatePrediction(pred.copy(isCorrect = isCorrect))
        return@withContext (updatedRows > 0)
    }
}