package com.tt.honeyDue.sharing

import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.core.content.FileProvider
import com.tt.honeyDue.data.DataManager
import com.tt.honeyDue.models.HoneyDueShareCodec
import com.tt.honeyDue.models.JoinResidenceResponse
import com.tt.honeyDue.models.Residence
import com.tt.honeyDue.network.APILayer
import com.tt.honeyDue.network.ApiResult
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File

/**
 * Manages residence share package creation and import via .honeydue files on Android.
 * Unlike contractors (which are exported client-side), residence sharing uses
 * server-generated share codes.
 */
object ResidenceSharingManager {

    /**
     * Creates a share Intent for a residence.
     * This first calls the backend to generate a share code, then creates the file.
     *
     * @param context Android context
     * @param residence The residence to share
     * @return Share Intent or null if creation failed
     */
    suspend fun createShareIntent(context: Context, residence: Residence): Intent? {
        return withContext(Dispatchers.IO) {
            try {
                // Generate share package from backend
                val result = APILayer.generateSharePackage(residence.id)

                when (result) {
                    is ApiResult.Success -> {
                        val sharedResidence = result.data
                        val jsonString = HoneyDueShareCodec.encodeSharedResidence(sharedResidence)
                        val fileName = HoneyDueShareCodec.safeShareFileName(residence.name)

                        // Create shared directory
                        val shareDir = File(context.cacheDir, "shared")
                        shareDir.mkdirs()

                        val file = File(shareDir, fileName)
                        file.writeText(jsonString)

                        val uri = FileProvider.getUriForFile(
                            context,
                            "${context.packageName}.fileprovider",
                            file
                        )

                        Intent(Intent.ACTION_SEND).apply {
                            type = "application/json"
                            putExtra(Intent.EXTRA_STREAM, uri)
                            putExtra(Intent.EXTRA_SUBJECT, "Join my residence: ${residence.name}")
                            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                        }
                    }
                    is ApiResult.Error -> {
                        null
                    }
                    else -> null
                }
            } catch (e: Exception) {
                e.printStackTrace()
                null
            }
        }
    }

    /**
     * Imports (joins) a residence from a content URI containing a share code.
     *
     * @param context Android context
     * @param uri The content URI of the .honeydue file
     * @return ApiResult with the JoinResidenceResponse on success, or error on failure
     */
    suspend fun importResidence(context: Context, uri: Uri): ApiResult<JoinResidenceResponse> {
        return withContext(Dispatchers.IO) {
            try {
                // Check authentication
                if (DataManager.authToken.value == null) {
                    return@withContext ApiResult.Error("You must be logged in to join a residence", 401)
                }

                // Read file content
                val inputStream = context.contentResolver.openInputStream(uri)
                    ?: return@withContext ApiResult.Error("Could not open file")

                val jsonString = inputStream.bufferedReader().use { it.readText() }
                inputStream.close()

                val shareCode = HoneyDueShareCodec.extractResidenceShareCodeOrNull(jsonString)
                    ?: return@withContext ApiResult.Error("Invalid residence share package")

                // Call API with share code
                APILayer.joinWithCode(shareCode)
            } catch (e: Exception) {
                e.printStackTrace()
                ApiResult.Error("Failed to join residence: ${e.message}")
            }
        }
    }
}
