package pl.firmatpp.kierowca.data.upload

import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test

class OfflineOutboxManagerTest {
    @Test
    fun recognizesLegacyCancellationFailureDetails() {
        assertTrue(isWorkerCancellationFailure("Typ: błąd aplikacji\nKomunikat: Job was cancelled"))
        assertTrue(isWorkerCancellationFailure("kotlinx.coroutines.JobCancellationException"))
        assertFalse(isWorkerCancellationFailure("HTTP 422: Niepoprawne zdjęcie"))
        assertFalse(isWorkerCancellationFailure(null))
    }

    @Test
    fun repairsInterruptedAndRetryablePhotoUploadsButNotRealPermanentFailures() {
        assertTrue(shouldRepairPhotoUpload(PhotoUploadStatus.Pending.storageValue, null))
        assertTrue(shouldRepairPhotoUpload(PhotoUploadStatus.Uploading.storageValue, null))
        assertTrue(shouldRepairPhotoUpload(PhotoUploadStatus.Verifying.storageValue, null))
        assertTrue(shouldRepairPhotoUpload(PhotoUploadStatus.FailedRetryable.storageValue, "timeout"))
        assertTrue(shouldRepairPhotoUpload(PhotoUploadStatus.FailedPermanent.storageValue, "Job was cancelled"))
        assertFalse(shouldRepairPhotoUpload(PhotoUploadStatus.FailedPermanent.storageValue, "HTTP 422"))
        assertFalse(shouldRepairPhotoUpload(PhotoUploadStatus.Cancelled.storageValue, null))
    }

    @Test
    fun repairsInterruptedRouteActionWithItsOriginalIdempotencyKey() {
        assertTrue(shouldRepairRouteAction(RouteActionStatus.Pending, null))
        assertTrue(shouldRepairRouteAction(RouteActionStatus.WaitingForPhotos, null))
        assertTrue(shouldRepairRouteAction(RouteActionStatus.Syncing, null))
        assertTrue(shouldRepairRouteAction(RouteActionStatus.FailedRetryable, "timeout"))
        assertTrue(shouldRepairRouteAction(RouteActionStatus.FailedPermanent, "Job was cancelled"))
        assertTrue(
            shouldRepairRouteAction(
                RouteActionStatus.FailedPermanent,
                "Wymagane zdjęcie nie zostało wysłane. Popraw zdjęcie i ponów potwierdzenie etapu.",
            ),
        )
        assertFalse(shouldRepairRouteAction(RouteActionStatus.FailedPermanent, "Brakuje zdjęcia"))
        assertFalse(shouldRepairRouteAction(RouteActionStatus.FailedConflict, "Kurs już rozpoczęty"))
    }
}
