package com.cottondb.android import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import com.cottondb.android.core.CottonCalling import com.cottondb.android.core.CottonEvent import com.cottondb.android.core.MalformedCoreEventException import com.cottondb.android.navigation.Route import com.cottondb.android.work.money.MoneyFormState import com.cottondb.android.work.money.MoneyRecordVerb import com.cottondb.android.work.money.MoneyWriteResult import java.time.Clock import java.time.Instant import java.time.ZoneOffset import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNotSame import org.junit.Assert.assertNull import org.junit.Assert.assertSame import org.junit.Assert.assertTrue import org.junit.Test import org.junit.runner.RunWith /** Android-main lifetime checks for retained record and deletion visits. */ @RunWith(AndroidJUnit4::class) class MoneyWriteVisitsTest { private val fixtures = CopyOnWriteArrayList() @After fun closeFixtures() { onMain { fixtures.forEach(Fixture::close) fixtures.clear() } } @Test fun deletionConsumesItsReceiptOnceAndRetirementRefusesFurtherActions() { val fixture = onMain { fixture() } val deletion = onMain { fixture.models.deletion("transaction-1") } val job = onMain { requireNotNull(deletion.deleteConfirmed()) } runBlocking { job.join() } InstrumentationRegistry.getInstrumentation().waitForIdleSync() assertTrue(onMain { deletion.consumeDeleted() }) assertFalse(onMain { deletion.consumeDeleted() }) assertNull(onMain { deletion.deleteConfirmed() }) assertEquals(1, fixture.core.deleteCalls) onMain { fixture.models.retain(emptyList()) } assertNull(onMain { deletion.deleteConfirmed() }) assertEquals(1, fixture.core.deleteCalls) } private fun fixture(blockRecord: Boolean = false, malformedRecord: Boolean = false) = Fixture(blockRecord, malformedRecord).also(fixtures::add) private fun onMain(block: () -> T): T { var result: Result? = null InstrumentationRegistry.getInstrumentation().runOnMainSync { result = runCatching(block) } return requireNotNull(result).getOrThrow() } private class Fixture(blockRecord: Boolean, malformedRecord: Boolean) { private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) val core = WriteCore(blockRecord, malformedRecord) val models = MoneyModels( core = core, clock = Clock.fixed(Instant.parse("2026-09-22T23:30:00Z"), ZoneOffset.UTC), zone = java.time.ZoneId.of("Asia/Kolkata"), scope = scope, ) fun close() = scope.cancel() } private class WriteCore( private val blockRecord: Boolean, private val malformedRecord: Boolean, ) : CottonCalling { override val events: SharedFlow = MutableSharedFlow() override val eventErrors: SharedFlow = MutableSharedFlow() val writeArgs = CopyOnWriteArrayList() val recordEntered = CountDownLatch(1) private val recordReply = CompletableDeferred() var deleteCalls = 0 private set override suspend fun call(method: String, request: JsonObject): JsonElement = when (method) { "read.moneyForm" -> json(FORM) "write" -> write(request) else -> error("Unexpected core method: $method") } override suspend fun close() = Unit fun releaseRecord() { recordReply.complete(json(RECORD)) } private suspend fun write(request: JsonObject): JsonElement { val tool = request["tool"]!!.jsonPrimitive.content val args = request["args"]!!.jsonObject return when (tool) { "record_transaction" -> { writeArgs += args if (malformedRecord) json("""{"answer":{"id":"transaction-1"}}""") else if (blockRecord) { recordEntered.countDown() withContext(NonCancellable) { recordReply.await() } } else json(RECORD) } "delete_transaction" -> { deleteCalls += 1 json("""{"answer":{"deleted":true,"id":"transaction-1","description":"Lunch","occurredOn":"2026-09-23"}}""") } else -> error("Unexpected money tool: $tool") } } } private companion object { fun json(raw: String): JsonElement = Json.parseToJsonElement(raw) const val FORM = """{"currency":"INR","accounts":[ {"id":"bank","name":"Bank","kind":"asset","subtype":"bank","personId":null,"currency":"INR","institution":null,"numberMask":null,"archived":false,"balanceMinor":0,"postedBalanceMinor":null,"counts":null,"coverage":null,"gaps":[],"lastStatement":null}, {"id":"food","name":"Food","kind":"expense","subtype":"category","personId":null,"currency":"INR","institution":null,"numberMask":null,"archived":false,"balanceMinor":0,"postedBalanceMinor":null,"counts":null,"coverage":null,"gaps":[],"lastStatement":null}, {"id":"other-food","name":"Other food","kind":"expense","subtype":"category","personId":null,"currency":"INR","institution":null,"numberMask":null,"archived":false,"balanceMinor":0,"postedBalanceMinor":null,"counts":null,"coverage":null,"gaps":[],"lastStatement":null}],"people":[{"id":"person-1","fullName":"Synthetic person"}]}""" const val RECORD = """{"answer":{"id":"transaction-1","verb":"spent","occurredOn":"2026-09-23","description":"Lunch","amountMinor":1250,"personId":null,"lines":[{"accountId":"bank","account":"Bank","amountMinor":-1250},{"accountId":"food","account":"Food","amountMinor":1250}]}}""" } }