/*
 * Copyright © Harsh Shandilya.
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 */
package dev.msfjarvis.claw.android.viewmodel

import android.util.Log
import app.cash.sqldelight.coroutines.asFlow
import app.cash.sqldelight.coroutines.mapToList
import dev.msfjarvis.claw.android.BuildConfig
import dev.msfjarvis.claw.core.coroutines.DatabaseReadDispatcher
import dev.msfjarvis.claw.core.coroutines.DatabaseWriteDispatcher
import dev.msfjarvis.claw.database.local.SavedPost
import dev.msfjarvis.claw.database.local.SavedPostQueries
import dev.msfjarvis.claw.model.UIPost
import dev.msfjarvis.claw.model.toSavedPost
import dev.zacsweers.metro.Inject
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.withContext

@Inject
class SavedPostsRepository(
  private val savedPostQueries: SavedPostQueries,
  @param:DatabaseReadDispatcher private val readDispatcher: CoroutineDispatcher,
  @param:DatabaseWriteDispatcher private val writeDispatcher: CoroutineDispatcher,
) {
  val savedPosts = savedPostQueries.selectAllPosts().asFlow().mapToList(readDispatcher)
  val savedPostsSortedByDate =
    savedPostQueries.selectAllPostsSortedByDate().asFlow().mapToList(readDispatcher)

  fun getPostsFromLastNDays(days: Long) =
    savedPostQueries.selectPostsFromLastNDays(days.toString()).asFlow().mapToList(readDispatcher)

  fun getRecentPosts(limit: Long) =
    savedPostQueries.selectRecentPosts(limit).asFlow().mapToList(readDispatcher)

  suspend fun toggleSave(post: UIPost) {
    val exists =
      withContext(readDispatcher) { savedPostQueries.postExists(post.shortId).executeAsOne() }
    if (exists) {
      if (BuildConfig.DEBUG) {
        Log.d(TAG, "Removing post: ${post.shortId}")
      }
      withContext(writeDispatcher) { savedPostQueries.deletePost(post.shortId) }
    } else {
      if (BuildConfig.DEBUG) {
        Log.d(TAG, "Saving post: ${post.shortId}")
      }
      withContext(writeDispatcher) { savedPostQueries.insertOrReplacePost(post.toSavedPost()) }
    }
  }

  suspend fun savePosts(posts: List<SavedPost>) {
    if (BuildConfig.DEBUG) {
      Log.d(TAG, "Saving posts: ${posts.joinToString(",") { it.shortId }}")
    }
    withContext(writeDispatcher) {
      savedPostQueries.transaction {
        posts.forEach { post -> savedPostQueries.insertOrReplacePost(post) }
      }
    }
  }

  private companion object {
    private const val TAG = "SavedPostsRepository"
  }
}
