package com.example.coloricam

import android.content.Context
import androidx.room.*
import kotlinx.coroutines.flow.Flow

@Entity(tableName = "meals")
data class Meal(
    @PrimaryKey(autoGenerate = true) val id: Int = 0,
    val date: Long,
    val name: String = "Repas",
    val analysisText: String,
    val totalCalories: Int,
    val type: String = "Collation"
)

@Entity(tableName = "glycemia")
data class Glycemia(
    @PrimaryKey(autoGenerate = true) val id: Int = 0,
    val date: Long,
    val value: Double,
    val moment: String
)

@Entity(tableName = "sports")
data class SportActivity(
    @PrimaryKey val id: Long,
    val name: String,
    val type: String,
    val distance: Float,
    val movingTime: Int,
    val calories: Float?,
    val date: Long // timestamp
)

@Dao
interface AppDao {
    @Insert suspend fun insertMeal(meal: Meal): Long
    @Delete suspend fun deleteMeal(meal: Meal)
    @Query("SELECT * FROM meals ORDER BY date DESC") fun getAllMeals(): Flow<List<Meal>>
    
    @Insert suspend fun insertGlycemia(glycemia: Glycemia): Long
    @Delete suspend fun deleteGlycemia(glycemia: Glycemia)
    @Query("SELECT * FROM glycemia ORDER BY date DESC") fun getAllGlycemia(): Flow<List<Glycemia>>

    @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertSports(sports: List<SportActivity>)
    @Query("SELECT * FROM sports ORDER BY date DESC") fun getAllSports(): Flow<List<SportActivity>>
    @Query("SELECT * FROM sports WHERE date >= :startOfDay AND date < :endOfDay ORDER BY date DESC") 
    fun getSportsForDay(startOfDay: Long, endOfDay: Long): Flow<List<SportActivity>>
}

@Database(entities = [Meal::class, Glycemia::class, SportActivity::class], version = 5)
abstract class AppDatabase : RoomDatabase() {
    abstract fun appDao(): AppDao
    companion object {
        @Volatile private var INSTANCE: AppDatabase? = null
        fun getDatabase(context: Context): AppDatabase =
            INSTANCE ?: synchronized(this) {
                Room.databaseBuilder(context.applicationContext, AppDatabase::class.java, "app_db")
                    .fallbackToDestructiveMigration()
                    .build().also { INSTANCE = it }
            }
    }
}
