package com.swoosh.microblog.data.repository

import android.content.Context
import com.swoosh.microblog.data.AccountManager
import com.swoosh.microblog.data.api.ApiClient
import com.swoosh.microblog.data.api.GhostApiService
import com.swoosh.microblog.data.model.GhostTagFull
import com.swoosh.microblog.data.model.TagWrapper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class TagRepository(private val context: Context) {

    private val accountManager = AccountManager(context)

    private fun getApi(): GhostApiService {
        val account = accountManager.getActiveAccount()
            ?: throw IllegalStateException("No active account configured")
        return ApiClient.getService(account.blogUrl) { account.apiKey }
    }

    suspend fun fetchTags(): Result<List<GhostTagFull>> =
        withContext(Dispatchers.IO) {
            try {
                val response = getApi().getTags()
                if (response.isSuccessful) {
                    Result.success(response.body()!!.tags)
                } else {
                    Result.failure(Exception("API error ${response.code()}: ${response.errorBody()?.string()}"))
                }
            } catch (e: Exception) {
                Result.failure(e)
            }
        }

    suspend fun createTag(
        name: String,
        description: String? = null,
        accentColor: String? = null
    ): Result<GhostTagFull> =
        withContext(Dispatchers.IO) {
            try {
                val tag = GhostTagFull(
                    name = name,
                    description = description,
                    accent_color = accentColor
                )
                val response = getApi().createTag(TagWrapper(listOf(tag)))
                if (response.isSuccessful) {
                    Result.success(response.body()!!.tags.first())
                } else {
                    Result.failure(Exception("Create tag failed ${response.code()}: ${response.errorBody()?.string()}"))
                }
            } catch (e: Exception) {
                Result.failure(e)
            }
        }

    suspend fun updateTag(id: String, tag: GhostTagFull): Result<GhostTagFull> =
        withContext(Dispatchers.IO) {
            try {
                val response = getApi().updateTag(id, TagWrapper(listOf(tag)))
                if (response.isSuccessful) {
                    Result.success(response.body()!!.tags.first())
                } else {
                    Result.failure(Exception("Update tag failed ${response.code()}: ${response.errorBody()?.string()}"))
                }
            } catch (e: Exception) {
                Result.failure(e)
            }
        }

    suspend fun deleteTag(id: String): Result<Unit> =
        withContext(Dispatchers.IO) {
            try {
                val response = getApi().deleteTag(id)
                if (response.isSuccessful) {
                    Result.success(Unit)
                } else {
                    Result.failure(Exception("Delete tag failed ${response.code()}"))
                }
            } catch (e: Exception) {
                Result.failure(e)
            }
        }
}
