import Foundation
import SwiftData

/// Gemeinsame App-Group-Konfiguration für Hauptapp und Share Extension.
enum AppGroup {
    static let identifier = "group.nahbar.shared"

    /// Shared UserDefaults für die Kommunikation zwischen Hauptapp und Extension.
    static var userDefaults: UserDefaults {
        UserDefaults(suiteName: identifier) ?? .standard
    }

    // MARK: - Hauptapp: Standard-Store (Daten bleiben erhalten)

    /// ModelContainer für die Hauptapp – nutzt Standard-Speicherort (Daten-kompatibel).
    /// Versucht CloudKit; fällt bei Bedarf auf lokalen Store zurück.
    static let icloudSyncKey = "icloudSyncEnabled"

    static func makeMainContainer() -> ModelContainer {
        let schema = Schema([Person.self, Moment.self, LogEntry.self])
        let icloudEnabled = UserDefaults.standard.bool(forKey: icloudSyncKey)
        let cloudKit: ModelConfiguration.CloudKitDatabase = icloudEnabled ? .automatic : .none
        let config = ModelConfiguration(schema: schema, cloudKitDatabase: cloudKit)
        if let container = try? ModelContainer(for: schema, configurations: [config]) {
            return container
        }
        // Fallback: lokal ohne CloudKit
        let localConfig = ModelConfiguration(schema: schema, cloudKitDatabase: .none)
        if let container = try? ModelContainer(for: schema, configurations: [localConfig]) {
            return container
        }
        return try! ModelContainer(for: schema, configurations: [ModelConfiguration(isStoredInMemoryOnly: true)])
    }

    // MARK: - Share Extension: App-Group-Store (nur für Extension)

    /// Speichert eine Nachricht als ausstehenden Moment in der App Group.
    /// Die Hauptapp importiert diese beim nächsten Start.
    static func enqueueMoment(personName: String, text: String, type: String, source: String? = nil) {
        var queue = pendingMoments
        var entry: [String: String] = [
            "personName": personName,
            "text": text,
            "type": type,
            "createdAt": ISO8601DateFormatter().string(from: Date())
        ]
        if let source { entry["source"] = source }
        queue.append(entry)
        if let data = try? JSONSerialization.data(withJSONObject: queue) {
            userDefaults.set(data, forKey: "pendingMoments")
        }
    }

    static var pendingMoments: [[String: String]] {
        guard let data = userDefaults.data(forKey: "pendingMoments"),
              let array = try? JSONSerialization.jsonObject(with: data) as? [[String: String]]
        else { return [] }
        return array
    }

    static func clearPendingMoments() {
        userDefaults.removeObject(forKey: "pendingMoments")
    }

    // MARK: - Personenliste für Extension

    /// Hauptapp schreibt beim Start die Personenliste in UserDefaults,
    /// damit die Extension sie ohne Store-Zugriff lesen kann.
    static func savePeopleList(_ people: [Person]) {
        let list = people.map { ["id": $0.id.uuidString, "name": $0.name, "tag": $0.tagRaw] }
        if let data = try? JSONSerialization.data(withJSONObject: list) {
            userDefaults.set(data, forKey: "cachedPeople")
        }
    }

    static var cachedPeople: [[String: String]] {
        guard let data = userDefaults.data(forKey: "cachedPeople"),
              let array = try? JSONSerialization.jsonObject(with: data) as? [[String: String]]
        else { return [] }
        return array
    }
}
