package com.omixlab.lckcontrol.data.local.dao

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import com.omixlab.lckcontrol.data.local.entity.StreamDestinationEntity
import com.omixlab.lckcontrol.data.local.entity.StreamPlanEntity
import com.omixlab.lckcontrol.data.local.entity.StreamPlanWithDestinations
import kotlinx.coroutines.flow.Flow

@Dao
interface StreamPlanDao {
    @Transaction
    @Query("SELECT * FROM stream_plans ORDER BY createdAt DESC")
    fun observeAll(): Flow<List<StreamPlanWithDestinations>>

    @Transaction
    @Query("SELECT * FROM stream_plans ORDER BY createdAt DESC")
    suspend fun getAll(): List<StreamPlanWithDestinations>

    @Transaction
    @Query("SELECT * FROM stream_plans WHERE planId = :planId")
    suspend fun getById(planId: String): StreamPlanWithDestinations?

    @Transaction
    @Query("SELECT * FROM stream_plans WHERE planId = :planId")
    fun observeById(planId: String): Flow<StreamPlanWithDestinations?>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun upsertPlan(plan: StreamPlanEntity)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun upsertDestination(destination: StreamDestinationEntity)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun upsertDestinations(destinations: List<StreamDestinationEntity>)

    @Query("DELETE FROM stream_destinations WHERE planId = :planId")
    suspend fun deleteDestinations(planId: String)

    @Query("DELETE FROM stream_plans WHERE planId = :planId")
    suspend fun deletePlan(planId: String)

    @Query("UPDATE stream_plans SET status = :status WHERE planId = :planId")
    suspend fun updateStatus(planId: String, status: String)

    @Query("UPDATE stream_destinations SET rtmpUrl = :rtmpUrl, streamKey = :streamKey, broadcastId = :broadcastId, status = :status WHERE id = :id")
    suspend fun updateDestinationStream(id: String, rtmpUrl: String, streamKey: String, broadcastId: String, status: String)

    @Transaction
    suspend fun insertPlanWithDestinations(plan: StreamPlanEntity, destinations: List<StreamDestinationEntity>) {
        upsertPlan(plan)
        deleteDestinations(plan.planId)
        upsertDestinations(destinations)
    }
}
