/*
 * Copyright (c) 2026 Meshtastic LLC
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
package org.meshtastic.core.common.util

import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertTrue

@OptIn(ExperimentalCoroutinesApi::class)
class SequentialJobTest {

    private val sequentialJob = SequentialJob()

    @Test
    fun `launch cancels previous job`() = runTest {
        var job1Active = false
        var job1Cancelled = false

        // Launch first job
        sequentialJob.launch(this) {
            try {
                job1Active = true
                delay(1000)
            } finally {
                job1Cancelled = true
            }
        }

        advanceTimeBy(100)
        assertTrue(job1Active, "Job 1 should be active")

        // Launch second job
        sequentialJob.launch(this) {
            // Do nothing
        }

        advanceTimeBy(100)
        assertTrue(job1Cancelled, "Job 1 should be cancelled")
    }

    @Test
    fun `cancel stops the job`() = runTest {
        var jobActive = false
        var jobCancelled = false

        sequentialJob.launch(this) {
            try {
                jobActive = true
                delay(1000)
            } finally {
                jobCancelled = true
            }
        }

        advanceTimeBy(100)
        assertTrue(jobActive, "Job should be active")

        sequentialJob.cancel()

        advanceTimeBy(100)
        assertTrue(jobCancelled, "Job should be cancelled")
    }
}
