/*
 * Hermes Node Android
 * Copyright (C) 2026 Stefy Lanza <stefy@nexlab.net>
 * SPDX-License-Identifier: GPL-3.0-or-later
 */
package net.nexlab.hermesnodeandroid

import android.content.Context
import org.json.JSONObject

object VideoCaptureSessionStore {
    private const val PREFS = "hermes_node_android_video_capture"
    private const val KEY_PENDING = "pending_request"
    private const val KEY_LAST_RESULT = "last_result"

    fun savePending(context: Context, payload: JSONObject) {
        context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
            .putString(KEY_PENDING, payload.toString())
            .apply()
    }

    fun loadPending(context: Context): JSONObject? {
        val raw = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY_PENDING, null) ?: return null
        return runCatching { JSONObject(raw) }.getOrNull()
    }

    fun clearPending(context: Context) {
        context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().remove(KEY_PENDING).apply()
    }

    fun saveResult(context: Context, payload: JSONObject) {
        context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
            .putString(KEY_LAST_RESULT, payload.toString())
            .apply()
    }

    fun loadResult(context: Context): JSONObject? {
        val raw = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY_LAST_RESULT, null) ?: return null
        return runCatching { JSONObject(raw) }.getOrNull()
    }

    fun consumeResult(context: Context, requestId: String): JSONObject? {
        val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
        val raw = prefs.getString(KEY_LAST_RESULT, null) ?: return null
        val obj = runCatching { JSONObject(raw) }.getOrNull() ?: return null
        if (obj.optString("request_id") != requestId) return null
        prefs.edit().remove(KEY_LAST_RESULT).apply()
        return obj
    }

    fun clearResult(context: Context) {
        context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().remove(KEY_LAST_RESULT).apply()
    }
}
