import SwiftData
import SwiftUI

struct ContentView: View {
    @Environment(ConnectionManager.self) private var manager
    @Environment(\.modelContext) private var modelContext

    var body: some View {
        Group {
            switch manager.screen {
            case .login:
                LoginView()
            case .connecting:
                ConnectingView()
            case .forms:
                RemoteFormView()
            case .chat:
                ChatView()
            }
        }
        .animation(.default, value: manager.screen)
        .onAppear {
            manager.modelContext = modelContext
            purgeExpiredMessages()
        }
    }

    private func purgeExpiredMessages() {
        // Purge all if save is off
        if !UserDefaults.standard.bool(forKey: "save_messages", default: true) {
            try? modelContext.delete(model: SavedMessage.self)
            try? modelContext.save()
            return
        }

        // Purge expired messages
        let deleteAfterRaw = UserDefaults.standard.integer(forKey: "delete_after")
        let days = deleteAfterRaw == 0 ? 0 : (DeleteAfter(rawValue: deleteAfterRaw) ?? .oneMonth).rawValue
        if days > 0 {
            let cutoff = Calendar.current.date(byAdding: .day, value: -days, to: .now) ?? .now
            let expired = FetchDescriptor<SavedMessage>(
                predicate: #Predicate { $0.timestamp < cutoff }
            )
            if let old = try? modelContext.fetch(expired) {
                for message in old { modelContext.delete(message) }
            }
        }

        // Purge debug messages if not saving them
        if !UserDefaults.standard.bool(forKey: "save_debug_buffer") {
            let debugDesc = FetchDescriptor<SavedMessage>(
                predicate: #Predicate { $0.buffer == "debug" }
            )
            if let debugMsgs = try? modelContext.fetch(debugDesc) {
                for message in debugMsgs { modelContext.delete(message) }
            }
        }

        try? modelContext.save()
    }
}
