package aza.instant

import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import aza.instant.network.BackendClient
import io.ktor.client.call.body
import java.io.File

class UploadWorker(
    appContext: Context,
    workerParams: WorkerParameters
) : CoroutineWorker(appContext, workerParams) {

    override suspend fun doWork(): Result {
        val originalPhotoPath = inputData.getString("originalPhotoPath") ?: return Result.failure()
        val editedPhotoPath = inputData.getString("editedPhotoPath") ?: return Result.failure()
        val urlName = inputData.getString("urlName") ?: return Result.failure()

        val originalPhoto = File(originalPhotoPath)
        val editedPhoto = File(editedPhotoPath)

        return try {
            val backendClient = BackendClient()
            val response = backendClient.uploadImage(
                ownerKey = urlName,
                originalPhoto = originalPhoto,
                editedPhoto = editedPhoto
            )

            if (response.status.value in 200..299) {
                showUploadSuccessNotification()
                Result.success()
            } else {
                Log.e("UploadWorker", "Upload failed with status code: ${response.status.value}, body is ${response.body<String>()}")
                Result.failure()
            }
        } catch (e: Exception) {
            Log.e("UploadWorker", "Upload failed", e)
            Result.failure()
        }
    }

    private fun showUploadSuccessNotification() {
        val notificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val channelId = "upload_success_channel"

        notificationManager.createNotificationChannel(
            NotificationChannel(channelId, "Upload Success", NotificationManager.IMPORTANCE_DEFAULT))

        val notification = NotificationCompat.Builder(applicationContext, channelId)
            .setContentTitle("Upload Successful")
            .setContentText("Your photo has been successfully uploaded.")
            .setSmallIcon(R.mipmap.ic_launcher) // Replace with a real icon
            .build()

        notificationManager.notify(1, notification)
    }
}
