import Foundation

public struct EmailAddress: Sendable, Codable, Equatable, Hashable {
	public var name: String?
	public var address: String

	public init(name: String? = nil, address: String) {
		self.name = name
		self.address = address
	}

	public var displayName: String {
		name ?? address
	}

	/// Parses "Alice <alice@example.com>" or bare "alice@example.com"
	public static func parse(_ raw: String) -> EmailAddress {
		let trimmed = raw.trimmingCharacters(in: .whitespaces)
		guard let openAngle = trimmed.lastIndex(of: "<"),
			  let closeAngle = trimmed.lastIndex(of: ">"),
			  openAngle < closeAngle
		else {
			return EmailAddress(address: trimmed)
		}
		let addr = String(trimmed[trimmed.index(after: openAngle)..<closeAngle])
		let namepart = String(trimmed[..<openAngle]).trimmingCharacters(in: .whitespaces)
		return EmailAddress(
			name: namepart.isEmpty ? nil : namepart.trimmingCharacters(in: CharacterSet(charactersIn: "\"")),
			address: addr
		)
	}
}
