package com.tt.honeyDue.models

import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

/**
 * Shared encoder/decoder for `.honeydue` payloads across Android and iOS.
 *
 * This keeps package JSON shape in one place while each platform owns
 * native share-sheet presentation details.
 */
object HoneyDueShareCodec {
    private val json = Json {
        prettyPrint = true
        ignoreUnknownKeys = true
        encodeDefaults = true
    }

    fun encodeContractorPackage(contractor: Contractor, exportedBy: String? = null): String {
        return encodeSharedContractor(contractor.toSharedContractor(exportedBy))
    }

    fun encodeSharedContractor(sharedContractor: SharedContractor): String {
        return json.encodeToString(SharedContractor.serializer(), sharedContractor)
    }

    fun encodeSharedResidence(sharedResidence: SharedResidence): String {
        return json.encodeToString(SharedResidence.serializer(), sharedResidence)
    }

    fun decodeSharedContractorOrNull(jsonContent: String): SharedContractor? {
        return try {
            json.decodeFromString(SharedContractor.serializer(), jsonContent)
        } catch (_: Exception) {
            null
        }
    }

    fun decodeSharedResidenceOrNull(jsonContent: String): SharedResidence? {
        return try {
            json.decodeFromString(SharedResidence.serializer(), jsonContent)
        } catch (_: Exception) {
            null
        }
    }

    fun createContractorImportRequestOrNull(
        jsonContent: String,
        availableSpecialties: List<ContractorSpecialty>
    ): ContractorCreateRequest? {
        val shared = decodeSharedContractorOrNull(jsonContent) ?: return null
        val specialtyIds = shared.resolveSpecialtyIds(availableSpecialties)
        return shared.toCreateRequest(specialtyIds)
    }

    fun extractResidenceShareCodeOrNull(jsonContent: String): String? {
        return decodeSharedResidenceOrNull(jsonContent)?.shareCode
    }

    /**
     * Build a filesystem-safe package filename with `.honeydue` extension.
     */
    fun safeShareFileName(displayName: String): String {
        val safeName = displayName
            .replace(" ", "_")
            .replace("/", "-")
            .take(50)
        return "$safeName.honeydue"
    }
}
