import SwiftUI
import Models

@Observable
@MainActor
final class AccountSetupViewModel {
	var email: String = ""
	var password: String = ""
	var imapHost: String = ""
	var imapPort: String = "993"
	var smtpHost: String = ""
	var smtpPort: String = "587"
	var smtpSecurity: SMTPSecurity = .starttls
	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
			&& !smtpHost.isEmpty && !smtpPort.isEmpty
	}

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

		if let config = await AutoDiscovery.discover(for: email) {
			if let imap = config.imap {
				imapHost = imap.hostname
				imapPort = String(imap.port)
			}
			if let smtp = config.smtp {
				smtpHost = smtp.hostname
				smtpPort = String(smtp.port)
				smtpSecurity = smtp.socketType.uppercased() == "SSL" ? .ssl : .starttls
			}
			isAutoDiscovering = false
			// If neither was found, treat as failure
			if config.imap == nil && config.smtp == nil {
				autoDiscoveryFailed = true
				isManualMode = true
			}
		} else {
			isAutoDiscovering = false
			autoDiscoveryFailed = true
			isManualMode = true
		}
	}

	func buildConfig() -> (AccountConfig, Credentials)? {
		guard let imapPortInt = Int(imapPort),
			  let smtpPortInt = Int(smtpPort),
			  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: imapPortInt,
			smtpHost: smtpHost,
			smtpPort: smtpPortInt,
			smtpSecurity: smtpSecurity
		)
		let credentials = Credentials(username: email, password: password)
		return (config, credentials)
	}
}
