import Foundation

public extension JSONDecoder.DateDecodingStrategy {
    static var comprehensive: Self {
        .custom { decoder in
            let container = try decoder.singleValueContainer()
            let dateString = try container.decode(String.self)

            // Try default ISO8601DateFormatter first
            let formatter = ISO8601DateFormatter()
            formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]

            if let date = formatter.date(from: dateString) {
                return date
            }

            // Try extended formats if default fails
            let extendedFormatter = ISO8601DateFormatter()
            extendedFormatter.formatOptions = [
                .withInternetDateTime,
                .withFractionalSeconds,
                .withSpaceBetweenDateAndTime, // Allows spaces instead of T
            ]

            if let date = extendedFormatter.date(from: dateString) {
                return date
            }

            // Try without timezone
            let noTimezoneFormatter = ISO8601DateFormatter()
            noTimezoneFormatter.formatOptions = [.withFullDate, .withFullTime, .withFractionalSeconds]

            if let date = noTimezoneFormatter.date(from: dateString) {
                return date
            }

            // Try date only formats
            let dateOnlyFormatter = ISO8601DateFormatter()
            dateOnlyFormatter.formatOptions = [.withFullDate]

            if let date = dateOnlyFormatter.date(from: dateString) {
                return date
            }

            // Try basic format (no separators)
            let basicFormatter = ISO8601DateFormatter()
            basicFormatter.formatOptions = [.withYear, .withMonth, .withDay, .withTime]

            if let date = basicFormatter.date(from: dateString) {
                return date
            }

            // If all fail, use custom date formatter for edge cases
            let fallbackFormatter = DateFormatter()
            fallbackFormatter.locale = Locale(identifier: "en_US_POSIX")
            fallbackFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

            if let date = fallbackFormatter.date(from: dateString) {
                return date
            }

            throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid date format: \(dateString)")
        }
    }
}
