package pl.firmatpp.kierowca.data.upload

import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import pl.firmatpp.kierowca.data.model.RoutePhotoDto

class PhotoUploadReconciliationTest {
    @Test
    fun serverReceiptIdentityClearsFalseLocalFailure() {
        val upload = upload(
            clientRequestId = "request-1",
            contentSha256 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
        )

        assertTrue(serverPhotoConfirmsUpload(upload, serverPhoto("request-1", upload.contentSha256.uppercase())))
        assertFalse(serverPhotoConfirmsUpload(upload, serverPhoto("request-2", upload.contentSha256)))
        assertFalse(serverPhotoConfirmsUpload(upload, serverPhoto("request-1", "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")))
    }

    @Test
    fun legacyServerPhotoWithoutHashStillConfirmsMatchingRequestId() {
        val upload = upload("request-1", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")

        assertTrue(serverPhotoConfirmsUpload(upload, serverPhoto("request-1", null)))
    }

    private fun upload(clientRequestId: String, contentSha256: String): PhotoUploadEntity =
        PhotoUploadEntity(
            clientRequestId = clientRequestId,
            routeId = "10",
            localPath = "/tmp/$clientRequestId.jpg",
            source = "camera",
            takenAt = null,
            latitude = null,
            longitude = null,
            locationAccuracyMeters = null,
            mimeType = "image/jpeg",
            size = 100,
            contentSha256 = contentSha256,
            status = PhotoUploadStatus.FailedPermanent.storageValue,
            lastError = "Typ: błąd aplikacji\nKomunikat: Job was cancelled",
        )

    private fun serverPhoto(clientRequestId: String, contentSha256: String?): RoutePhotoDto =
        RoutePhotoDto(
            id = "42",
            routeId = "10",
            clientRequestId = clientRequestId,
            contentSha256 = contentSha256,
            source = "camera",
            stage = "loading",
            mimeType = "image/jpeg",
            size = 100,
            url = "https://example.test/photo/42",
            takenAt = null,
            latitude = null,
            longitude = null,
            locationAccuracyMeters = null,
            createdAt = null,
        )
}
