package com.rssuper.database.daos

import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import com.rssuper.database.entities.SubscriptionEntity
import kotlinx.coroutines.flow.Flow
import java.util.Date

@Dao
interface SubscriptionDao {
    @Query("SELECT * FROM subscriptions ORDER BY title ASC")
    fun getAllSubscriptions(): Flow<List<SubscriptionEntity>>
    
    @Query("SELECT * FROM subscriptions WHERE id = :id")
    suspend fun getSubscriptionById(id: String): SubscriptionEntity?
    
    @Query("SELECT * FROM subscriptions WHERE url = :url")
    suspend fun getSubscriptionByUrl(url: String): SubscriptionEntity?
    
    @Query("SELECT * FROM subscriptions WHERE enabled = 1 ORDER BY title ASC")
    fun getEnabledSubscriptions(): Flow<List<SubscriptionEntity>>
    
    @Query("SELECT * FROM subscriptions WHERE category = :category ORDER BY title ASC")
    fun getSubscriptionsByCategory(category: String): Flow<List<SubscriptionEntity>>
    
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertSubscription(subscription: SubscriptionEntity): Long
    
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertSubscriptions(subscriptions: List<SubscriptionEntity>): List<Long>
    
    @Update
    suspend fun updateSubscription(subscription: SubscriptionEntity): Int
    
    @Delete
    suspend fun deleteSubscription(subscription: SubscriptionEntity): Int
    
    @Query("DELETE FROM subscriptions WHERE id = :id")
    suspend fun deleteSubscriptionById(id: String): Int
    
    @Query("SELECT COUNT(*) FROM subscriptions")
    fun getSubscriptionCount(): Flow<Int>
    
    @Query("UPDATE subscriptions SET error = :error WHERE id = :id")
    suspend fun updateError(id: String, error: String?)
    
    @Query("UPDATE subscriptions SET lastFetchedAt = :lastFetchedAt, error = NULL WHERE id = :id")
    suspend fun updateLastFetchedAt(id: String, lastFetchedAt: Date)
    
    @Query("UPDATE subscriptions SET nextFetchAt = :nextFetchAt WHERE id = :id")
    suspend fun updateNextFetchAt(id: String, nextFetchAt: Date)
}
