@testable import APIClient
import Foundation
import Testing

@Test("discover sections parse")
func testDiscoverSectionsParse() async throws {
    let discoverJSONData = try fixtureData(for: "api-discover.txt")

    do {
        let decoder = JSONDecoder()
        decoder.keyDecodingStrategy = .convertFromSnakeCase
        decoder.dateDecodingStrategy = .iso8601WithFractions
        let discoverSections = try decoder.decode(GenAPI.DiscoverResp.self, from: discoverJSONData)
        #expect(discoverSections.sections?.count == 3)
        print(String(describing: discoverSections.sections?.first?.object))
    } catch {
        print("\(error)")
        throw error
    }
}

func fixtureData(for fixture: String) throws -> Data {
    try Data(contentsOf: fixtureUrl(for: fixture))
}

func fixtureUrl(for fixture: String) -> URL {
    fixturesDirectory().appendingPathComponent(fixture)
}

func fixturesDirectory(path: String = #file) -> URL {
    let url = URL(fileURLWithPath: path)
    let testsDir = url.deletingLastPathComponent()
    let res = testsDir.appendingPathComponent("Fixtures")
    return res
}

@Test("Date parsing")
func testDateParsing() {
    // Testing examples
    let testDates = [
        "2023-10-24T14:30:45.123Z", // Full format with fractional seconds
        "2023-10-24T14:30:45Z", // Full format without fractional seconds
        "2023-10-24T14:30:45+05:30", // With timezone offset
        "2023-10-24 14:30:45Z", // With space instead of T
        "2023-10-24", // Date only
        "20231024T143045Z", // Basic format
    ]

    // Codable wrapper
    struct DateWrapper: Codable {
        let date: Date
    }

    let decoder = JSONDecoder()
    decoder.dateDecodingStrategy = .comprehensive

    for dateString in testDates {
        // Wrap the date string in a JSON object
        let jsonString = "{\"date\": \"\(dateString)\"}"
        guard let data = jsonString.data(using: .utf8) else { continue }

        let result = try? decoder.decode(DateWrapper.self, from: data)
        #expect(result?.date != nil)
    }
}
