WatchHealthUploadTimeList.swift 1.5 KB
import Foundation

/// Upload boundaries returned by GET `/client/doublefeel/health/v2/data_upload/common/`.
/// The API has existed in both direct and `{ "data": ... }` response shapes.
struct WatchHealthUploadTimeList: Decodable {
    struct Item: Decodable {
        let dataType: Int?
        let latestDataTime: TimeInterval?

        enum CodingKeys: String, CodingKey {
            case dataType = "data_type"
            case latestDataTime = "latest_data_time"
        }
    }

    let latestDataTimeList: [Item]

    private enum CodingKeys: String, CodingKey {
        case latestDataTimeList = "latest_data_time_list"
        case data
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        if let list = try container.decodeIfPresent([Item].self, forKey: .latestDataTimeList) {
            latestDataTimeList = list
            return
        }
        if let wrapped = try container.decodeIfPresent(WatchHealthUploadTimeList.self, forKey: .data) {
            latestDataTimeList = wrapped.latestDataTimeList
            return
        }
        throw DecodingError.dataCorruptedError(
            forKey: .latestDataTimeList,
            in: container,
            debugDescription: "Missing latest_data_time_list"
        )
    }

    func latestDate(for dataType: Int) -> Date? {
        latestDataTimeList
            .first { $0.dataType == dataType }?
            .latestDataTime
            .map(Date.init(timeIntervalSince1970:))
    }
}