
import Foundation

internal final class RemoteFeedLoaderParser {
	private init() {}

	private struct RemoteFeedImageRoot: Decodable {
		private let items: [RemoteFeedImage]

		var images: [FeedImage] {
			items.map { $0.feedImage }
		}
	}

	private struct RemoteFeedImage: Decodable {
		private let id: UUID
		private let description: String?
		private let location: String?
		private let url: URL

		private enum CodingKeys: String, CodingKey {
			case id = "image_id"
			case url = "image_url"
			case description = "image_desc"
			case location = "image_loc"
		}

		var feedImage: FeedImage {
			FeedImage(id: id, description: description, location: location, url: url)
		}
	}

	private static var OK_200 = 200

	static func map(data: Data, response: HTTPURLResponse) -> FeedLoader.Result {
		guard response.statusCode == OK_200,
		      let root = try? JSONDecoder().decode(RemoteFeedImageRoot.self, from: data) else {
			return .failure(RemoteFeedLoader.Error.invalidData)
		}
		return .success(root.images)
	}
}
