import Foundation
import Observation
import SwiftData

@Observable
@MainActor
final class AppSettingsStore {
    private let modelContext: ModelContext
    private(set) var settings: AppSettings

    init(modelContext: ModelContext) {
        self.modelContext = modelContext

        if let existing = Self.fetchSettings(in: modelContext).first {
            self.settings = existing
        } else {
            let newSettings = AppSettings()
            modelContext.insert(newSettings)
            self.settings = newSettings
            saveContext()
        }
    }

    var preferredShareAction: PreferredShareAction {
        get { PreferredShareAction(rawValue: settings.preferredShareActionRawValue) ?? .shareSheet }
        set {
            settings.preferredShareActionRawValue = newValue.rawValue
            settings.updatedAt = .now
            saveContext()
        }
    }

    var defaultFollowUpPreset: DefaultFollowUpPreset {
        get { DefaultFollowUpPreset(rawValue: settings.defaultFollowUpPresetRawValue) ?? .none }
        set {
            settings.defaultFollowUpPresetRawValue = newValue.rawValue
            settings.updatedAt = .now
            saveContext()
        }
    }

    private static func fetchSettings(in modelContext: ModelContext) -> [AppSettings] {
        let descriptor = FetchDescriptor<AppSettings>(
            sortBy: [SortDescriptor(\.createdAt, order: .forward)]
        )
        return (try? modelContext.fetch(descriptor)) ?? []
    }

    private func saveContext() {
        do {
            try modelContext.save()
        } catch {
            modelContext.rollback()
        }
    }
}
