package com.swoosh.microblog.data.db

import androidx.room.TypeConverter
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.swoosh.microblog.data.model.PostStatus
import com.swoosh.microblog.data.model.QueueStatus

class Converters {
    @TypeConverter
    fun fromPostStatus(value: PostStatus): String = value.name

    @TypeConverter
    fun toPostStatus(value: String): PostStatus = try {
        PostStatus.valueOf(value)
    } catch (_: Exception) {
        PostStatus.DRAFT
    }

    @TypeConverter
    fun fromQueueStatus(value: QueueStatus): String = value.name

    @TypeConverter
    fun toQueueStatus(value: String): QueueStatus = try {
        QueueStatus.valueOf(value)
    } catch (_: Exception) {
        QueueStatus.NONE
    }

    companion object {
        private val gson = Gson()

        /**
         * Serializes a list of strings to a JSON array string.
         * Returns null for null or empty lists.
         */
        fun stringListToJson(list: List<String>?): String? {
            if (list.isNullOrEmpty()) return null
            return gson.toJson(list)
        }

        /**
         * Deserializes a JSON array string to a list of strings.
         * Returns empty list for null or empty input.
         */
        fun jsonToStringList(json: String?): List<String> {
            if (json.isNullOrBlank()) return emptyList()
            return try {
                val type = object : TypeToken<List<String>>() {}.type
                gson.fromJson(json, type) ?: emptyList()
            } catch (e: Exception) {
                emptyList()
            }
        }
    }
}
