import Foundation

@Observable
final class MailViewModel {
	let apiClient: APIClient

	var threads: [ThreadSummary] = []
	var selectedThread: ThreadSummary?
	var selectedMessages: [EmailMessage] = []
	var selectedPerspective: Perspective = .inbox
	var isLoading = false
	var errorMessage: String?

	enum Perspective: String, CaseIterable, Identifiable {
		case inbox = "Inbox"
		case today = "Today"
		case archive = "Archive"

		var id: String { rawValue }

		var systemImage: String {
			switch self {
			case .inbox: "tray"
			case .today: "sun.max"
			case .archive: "archivebox"
			}
		}
	}

	init(apiClient: APIClient) {
		self.apiClient = apiClient
	}

	func loadThreads(accountId: String) async {
		isLoading = true
		errorMessage = nil
		do {
			threads = try await apiClient.fetchThreads(accountId: accountId)
		} catch {
			errorMessage = error.localizedDescription
		}
		isLoading = false
	}

	func loadMessages(for thread: ThreadSummary) async {
		selectedThread = thread
		do {
			selectedMessages = try await apiClient.fetchMessages(threadId: thread.threadId)
		} catch {
			errorMessage = error.localizedDescription
		}
	}

	func connectToEvents(baseURL: URL, accountId: String) {
		let sseURL = baseURL.appendingPathComponent("api/events")
		let sseClient = SSEClient(url: sseURL)

		sseClient.connect { [weak self] event in
			guard let self else { return }
			if event.event == "threads_updated" {
				Task { @MainActor in
					await self.loadThreads(accountId: accountId)
				}
			}
		}
	}
}
