import Foundation enum RedditSubmitURLBuilder { static func isSubmitPage(_ url: URL) -> Bool { guard let host = url.host?.lowercased(), host.contains("reddit.com") else { return false } return url.path.range(of: #"/r/[^/]+/submit"#, options: .regularExpression) != nil } static func submitURL(for draft: PostDraft) throws -> URL { try PostDraftValidator.validateForExport(draft) let subreddit = PostDraftValidator.normalizedSubreddit(draft.subreddit) var components = URLComponents() components.scheme = "https" components.host = "www.reddit.com" components.path = "/r/\(subreddit)/submit" var queryItems = [ URLQueryItem(name: "title", value: draft.title.trimmingCharacters(in: .whitespaces)), ] switch draft.postType { case .text: queryItems.append(URLQueryItem(name: "selftext", value: "true")) let body = draft.body.trimmingCharacters(in: .whitespaces) if !body.isEmpty { queryItems.append(URLQueryItem(name: "text", value: body)) } case .link: queryItems.append( URLQueryItem(name: "url", value: draft.linkURL.trimmingCharacters(in: .whitespaces)) ) case .image, .video: queryItems.append(URLQueryItem(name: "selftext", value: "true")) let body = draft.body.trimmingCharacters(in: .whitespaces) if !body.isEmpty { queryItems.append(URLQueryItem(name: "text", value: body)) } case .poll: let body = draft.body.trimmingCharacters(in: .whitespaces) if !body.isEmpty { queryItems.append(URLQueryItem(name: "text", value: body)) } } components.queryItems = queryItems guard let url = components.url else { throw PostDraftValidationError.invalidSubreddit } return url } }