package com.tt.honeyDue.widget

import android.content.Context
import android.os.Build
import androidx.glance.GlanceId
import androidx.glance.action.ActionParameters
import androidx.glance.action.actionParametersOf
import androidx.test.core.app.ApplicationProvider
import kotlinx.coroutines.test.runTest
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config

/**
 * Verifies the Glance [CompleteTaskAction] correctly pulls the task id from
 * [ActionParameters] and forwards to [WidgetActionProcessor.processComplete].
 */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [Build.VERSION_CODES.TIRAMISU])
class CompleteTaskActionTest {

    private lateinit var context: Context

    private data class Invocation(val context: Context, val taskId: Long)
    private val invocations = mutableListOf<Invocation>()

    @Before
    fun setUp() {
        context = ApplicationProvider.getApplicationContext()
        invocations.clear()
        // Swap the processor's entry point for a capturing spy.
        WidgetActionProcessor.processOverrideForTest = { ctx, id ->
            invocations += Invocation(ctx, id)
            WidgetActionProcessor.Result.Success
        }
    }

    @After
    fun tearDown() {
        WidgetActionProcessor.resetTestHooks()
    }

    private val dummyGlanceId: GlanceId = object : GlanceId {}

    @Test
    fun completeTaskAction_reads_taskId_from_parameters() = runTest {
        val action = CompleteTaskAction()
        val params = actionParametersOf(CompleteTaskAction.taskIdKey to 123L)

        action.onAction(context, dummyGlanceId, params)

        assertEquals(1, invocations.size)
        assertEquals(123L, invocations.single().taskId)
    }

    @Test
    fun completeTaskAction_missing_taskId_noOp() = runTest {
        val action = CompleteTaskAction()
        // No task_id parameter provided.
        val params: ActionParameters = actionParametersOf()

        action.onAction(context, dummyGlanceId, params)

        assertEquals(
            "processComplete must not be invoked when task_id is absent",
            0,
            invocations.size
        )
    }

    @Test
    fun completeTaskAction_taskIdKey_nameMatchesIos() {
        assertEquals("task_id", CompleteTaskAction.taskIdKey.name)
    }
}
