import CloudKit

/// Service for fetching shared cards from CloudKit public database.
struct ClipCloudKitService: Sendable {
    private let database: CKDatabase

    init(containerID: String = ClipIdentifiers.cloudKitContainerIdentifier) {
        self.database = CKContainer(identifier: containerID).publicCloudDatabase
    }

    /// Fetches a shared card from CloudKit by record name.
    /// - Parameter recordName: The UUID string identifying the record.
    /// - Returns: A snapshot of the shared card data.
    func fetchSharedCard(recordName: String) async throws -> SharedCardSnapshot {
        let recordID = CKRecord.ID(recordName: recordName)

        let record: CKRecord
        do {
            record = try await database.record(for: recordID)
        } catch {
            throw ClipError.fetchFailed
        }

        guard let vCardData = record["vCardData"] as? String else {
            throw ClipError.invalidRecord
        }

        if let expiresAt = record["expiresAt"] as? Date, expiresAt < .now {
            throw ClipError.expired
        }

        return SharedCardSnapshot(recordName: recordName, vCardData: vCardData)
    }
}
