import SwiftUI
import Models

@Observable
@MainActor
final class AccountSetupViewModel {
	var email: String = ""
	var password: String = ""
	var imapHost: String = ""
	var imapPort: String = "993"
	var accountName: String = ""

	var isAutoDiscovering = false
	var autoDiscoveryFailed = false
	var isManualMode = false
	var errorMessage: String?

	var canSubmit: Bool {
		!email.isEmpty && !password.isEmpty && !imapHost.isEmpty && !imapPort.isEmpty
	}

	func autoDiscover() async {
		guard !email.isEmpty else { return }
		isAutoDiscovering = true
		autoDiscoveryFailed = false

		if let server = await AutoDiscovery.discoverIMAP(for: email) {
			imapHost = server.hostname
			imapPort = String(server.port)
			isAutoDiscovering = false
		} else {
			isAutoDiscovering = false
			autoDiscoveryFailed = true
			isManualMode = true
		}
	}

	func buildConfig() -> (AccountConfig, Credentials)? {
		guard let port = Int(imapPort), canSubmit else { return nil }
		let id = email.replacingOccurrences(of: "@", with: "-at-")
			.replacingOccurrences(of: ".", with: "-")
		let config = AccountConfig(
			id: id,
			name: accountName.isEmpty ? email : accountName,
			email: email,
			imapHost: imapHost,
			imapPort: port
		)
		let credentials = Credentials(username: email, password: password)
		return (config, credentials)
	}
}
