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.GhostPage
import com.swoosh.microblog.data.model.PageWrapper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class PageRepository(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 }
    }

    fun getBlogUrl(): String? {
        return accountManager.getActiveAccount()?.blogUrl
    }

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

    suspend fun createPage(page: GhostPage): Result<GhostPage> =
        withContext(Dispatchers.IO) {
            try {
                val response = getApi().createPage(PageWrapper(listOf(page)))
                if (response.isSuccessful) {
                    Result.success(response.body()!!.pages.first())
                } else {
                    Result.failure(Exception("Create failed ${response.code()}: ${response.errorBody()?.string()}"))
                }
            } catch (e: Exception) {
                Result.failure(e)
            }
        }

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

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