package com.fabledsword.minstrel.cache.db.dao

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.fabledsword.minstrel.cache.db.entities.AuthSessionEntity
import kotlinx.coroutines.flow.Flow

@Dao
interface AuthSessionDao {
    @Query("SELECT * FROM auth_session WHERE id = 0")
    fun observe(): Flow<AuthSessionEntity?>

    @Query("SELECT * FROM auth_session WHERE id = 0")
    suspend fun get(): AuthSessionEntity?

    /** Upsert with both fields at once — used for first-run init. */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun upsert(row: AuthSessionEntity)

    /** Partial update: change only the session cookie. */
    @Query("UPDATE auth_session SET sessionCookie = :cookie WHERE id = 0")
    suspend fun setSessionCookie(cookie: String?)

    /** Partial update: change only the base URL. */
    @Query("UPDATE auth_session SET baseUrl = :baseUrl WHERE id = 0")
    suspend fun setBaseUrl(baseUrl: String)

    /** Partial update: change only the serialized user identity JSON. */
    @Query("UPDATE auth_session SET userJson = :userJson WHERE id = 0")
    suspend fun setUserJson(userJson: String?)

    /** Partial update: change only the theme override ("light"/"dark"/null=system). */
    @Query("UPDATE auth_session SET themeMode = :themeMode WHERE id = 0")
    suspend fun setThemeMode(themeMode: String?)

    /** Partial update: change only the stable client install id. */
    @Query("UPDATE auth_session SET clientId = :clientId WHERE id = 0")
    suspend fun setClientId(clientId: String?)

    /** Partial update: change only the serialized cache settings. */
    @Query("UPDATE auth_session SET cacheSettingsJson = :json WHERE id = 0")
    suspend fun setCacheSettingsJson(json: String?)

    /** Partial update: change only the per-device diagnostics opt-out. */
    @Query("UPDATE auth_session SET diagnosticsOptOut = :optOut WHERE id = 0")
    suspend fun setDiagnosticsOptOut(optOut: Boolean)
}
