import CloudKit

/// Represents a shared card in CloudKit public database.
/// NOT a SwiftData model - uses raw CKRecord for ephemeral sharing.
struct SharedCardRecord: Sendable {
    let recordID: CKRecord.ID
    let vCardData: String
    let expiresAt: Date
    let createdAt: Date

    static let recordType = "SharedCard"

    enum Field: String {
        case vCardData
        case expiresAt
        case createdAt
    }

    init(recordID: CKRecord.ID, vCardData: String, expiresAt: Date, createdAt: Date = .now) {
        self.recordID = recordID
        self.vCardData = vCardData
        self.expiresAt = expiresAt
        self.createdAt = createdAt
    }

    init?(record: CKRecord) {
        guard let vCardData = record[Field.vCardData.rawValue] as? String,
              let expiresAt = record[Field.expiresAt.rawValue] as? Date else {
            return nil
        }
        self.recordID = record.recordID
        self.vCardData = vCardData
        self.expiresAt = expiresAt
        self.createdAt = (record[Field.createdAt.rawValue] as? Date) ?? record.creationDate ?? .now
    }

    func toCKRecord() -> CKRecord {
        let record = CKRecord(recordType: Self.recordType, recordID: recordID)
        record[Field.vCardData.rawValue] = vCardData
        record[Field.expiresAt.rawValue] = expiresAt
        record[Field.createdAt.rawValue] = createdAt
        return record
    }
}
