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

import androidx.room.*
import com.atridad.ascently.data.model.ClimbType
import com.atridad.ascently.data.model.Problem
import kotlinx.coroutines.flow.Flow

@Dao
interface ProblemDao {

    @Query("SELECT * FROM problems ORDER BY updatedAt DESC")
    fun getAllProblems(): Flow<List<Problem>>

    @Query("SELECT * FROM problems WHERE id = :id")
    suspend fun getProblemById(id: String): Problem?

    @Query("SELECT * FROM problems WHERE gymId = :gymId ORDER BY updatedAt DESC")
    fun getProblemsByGym(gymId: String): Flow<List<Problem>>

    @Query("SELECT * FROM problems WHERE climbType = :climbType ORDER BY updatedAt DESC")
    fun getProblemsByClimbType(climbType: ClimbType): Flow<List<Problem>>

    @Query(
        "SELECT * FROM problems WHERE gymId = :gymId AND climbType = :climbType ORDER BY updatedAt DESC",
    )
    fun getProblemsByGymAndType(gymId: String, climbType: ClimbType): Flow<List<Problem>>

    @Query("SELECT * FROM problems WHERE isActive = 1 ORDER BY updatedAt DESC")
    fun getActiveProblems(): Flow<List<Problem>>

    @Query("SELECT * FROM problems WHERE gymId = :gymId AND isActive = 1 ORDER BY updatedAt DESC")
    fun getActiveProblemsByGym(gymId: String): Flow<List<Problem>>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertProblem(problem: Problem)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertProblems(problems: List<Problem>)

    @Update suspend fun updateProblem(problem: Problem)

    @Delete suspend fun deleteProblem(problem: Problem)

    @Query("DELETE FROM problems WHERE id = :id")
    suspend fun deleteProblemById(id: String)

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

    @Query("SELECT COUNT(*) FROM problems WHERE isActive = 1")
    suspend fun getActiveProblemsCount(): Int

    @Query(
        """
        SELECT * FROM problems
        WHERE (name LIKE '%' || :searchQuery || '%'
        OR description LIKE '%' || :searchQuery || '%'
        OR location LIKE '%' || :searchQuery || '%')
        ORDER BY updatedAt DESC
    """,
    )
    fun searchProblems(searchQuery: String): Flow<List<Problem>>

    @Query("SELECT COUNT(*) FROM problems")
    suspend fun getProblemsCount(): Int

    @Query("DELETE FROM problems")
    suspend fun deleteAllProblems()
}
