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.GhostMember
import com.swoosh.microblog.data.model.MembersResponse
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.time.Instant
import java.time.temporal.ChronoUnit

class MemberRepository(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 fetchMembers(
        page: Int = 1,
        limit: Int = 15,
        filter: String? = null
    ): Result<MembersResponse> = withContext(Dispatchers.IO) {
        try {
            val response = getApi().getMembers(
                limit = limit,
                page = page,
                filter = filter
            )
            if (response.isSuccessful) {
                Result.success(response.body()!!)
            } else {
                Result.failure(Exception("API error ${response.code()}: ${response.errorBody()?.string()}"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    suspend fun fetchMember(id: String): Result<GhostMember> = withContext(Dispatchers.IO) {
        try {
            val response = getApi().getMember(id)
            if (response.isSuccessful) {
                val members = response.body()!!.members
                if (members.isNotEmpty()) {
                    Result.success(members.first())
                } else {
                    Result.failure(Exception("Member not found"))
                }
            } else {
                Result.failure(Exception("API error ${response.code()}: ${response.errorBody()?.string()}"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    suspend fun fetchAllMembers(): Result<List<GhostMember>> = withContext(Dispatchers.IO) {
        try {
            val allMembers = mutableListOf<GhostMember>()
            var page = 1
            var hasMore = true

            while (hasMore && page <= 20) {
                val response = getApi().getMembers(limit = 50, page = page)
                if (response.isSuccessful) {
                    val body = response.body()!!
                    allMembers.addAll(body.members)
                    hasMore = body.meta?.pagination?.next != null
                    page++
                } else {
                    return@withContext Result.failure(
                        Exception("API error ${response.code()}: ${response.errorBody()?.string()}")
                    )
                }
            }
            Result.success(allMembers)
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    fun getMemberStats(members: List<GhostMember>): MemberStats {
        val total = members.size
        val free = members.count { it.status == "free" }
        val paid = members.count { it.status == "paid" }

        val oneWeekAgo = Instant.now().minus(7, ChronoUnit.DAYS)
        val newThisWeek = members.count { member ->
            member.created_at?.let {
                try {
                    Instant.parse(it).isAfter(oneWeekAgo)
                } catch (e: Exception) {
                    false
                }
            } ?: false
        }

        val openRates = members.mapNotNull { it.email_open_rate }
        val avgOpenRate = if (openRates.isNotEmpty()) openRates.average() else null

        // Calculate MRR from paid member subscriptions
        val mrr = members.filter { it.status == "paid" }.sumOf { member ->
            member.subscriptions?.sumOf { sub ->
                if (sub.status == "active") {
                    val amount = sub.price?.amount ?: 0
                    when (sub.price?.interval) {
                        "year" -> amount / 12
                        "month" -> amount
                        else -> amount
                    }
                } else 0
            } ?: 0
        }

        return MemberStats(
            total = total,
            free = free,
            paid = paid,
            newThisWeek = newThisWeek,
            avgOpenRate = avgOpenRate,
            mrr = mrr
        )
    }
}

data class MemberStats(
    val total: Int,
    val free: Int,
    val paid: Int,
    val newThisWeek: Int,
    val avgOpenRate: Double?,
    val mrr: Int
)
