package com.atridad.ascently.data.database.dao

import androidx.room.*
import com.atridad.ascently.data.model.ClimbSession
import com.atridad.ascently.data.model.SessionStatus
import kotlinx.coroutines.flow.Flow

@Dao
interface ClimbSessionDao {

    @Query("SELECT * FROM climb_sessions ORDER BY date DESC")
    fun getAllSessions(): Flow<List<ClimbSession>>

    @Query("SELECT * FROM climb_sessions WHERE id = :id")
    suspend fun getSessionById(id: String): ClimbSession?

    @Query("SELECT * FROM climb_sessions WHERE gymId = :gymId ORDER BY date DESC")
    fun getSessionsByGym(gymId: String): Flow<List<ClimbSession>>

    @Query("SELECT * FROM climb_sessions WHERE date = :date ORDER BY createdAt DESC")
    fun getSessionsByDate(date: String): Flow<List<ClimbSession>>

    @Query("SELECT * FROM climb_sessions WHERE date BETWEEN :startDate AND :endDate ORDER BY date DESC")
    fun getSessionsInDateRange(startDate: String, endDate: String): Flow<List<ClimbSession>>

    @Query("SELECT * FROM climb_sessions ORDER BY date DESC LIMIT :limit")
    fun getRecentSessions(limit: Int = 10): Flow<List<ClimbSession>>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertSession(session: ClimbSession)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertSessions(sessions: List<ClimbSession>)

    @Update
    suspend fun updateSession(session: ClimbSession)

    @Delete
    suspend fun deleteSession(session: ClimbSession)

    @Query("DELETE FROM climb_sessions WHERE id = :id")
    suspend fun deleteSessionById(id: String)

    @Query("SELECT COUNT(*) FROM climb_sessions")
    suspend fun getSessionsCount(): Int

    @Query("SELECT COUNT(*) FROM climb_sessions WHERE gymId = :gymId")
    suspend fun getSessionsCountByGym(gymId: String): Int

    @Query("SELECT COUNT(*) FROM climb_sessions WHERE date BETWEEN :startDate AND :endDate")
    suspend fun getSessionsCountInDateRange(startDate: String, endDate: String): Int

    @Query("SELECT DISTINCT date FROM climb_sessions ORDER BY date DESC")
    suspend fun getUniqueDates(): List<String>

    @Query("SELECT * FROM climb_sessions WHERE status = :status ORDER BY date DESC")
    fun getSessionsByStatus(status: SessionStatus): Flow<List<ClimbSession>>

    @Query("SELECT * FROM climb_sessions WHERE status = 'ACTIVE' ORDER BY date DESC LIMIT 1")
    suspend fun getActiveSession(): ClimbSession?

    @Query("DELETE FROM climb_sessions")
    suspend fun deleteAllSessions()

    @Query("SELECT * FROM climb_sessions WHERE status = 'ACTIVE' ORDER BY date DESC LIMIT 1")
    fun getActiveSessionFlow(): Flow<ClimbSession?>
}
