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 displayName: String
    let role: String
    let company: String
    let vCardData: String
    let expiresAt: Date
    let createdAt: Date

    static let recordType = "SharedCard"

    enum Field: String {
        case displayName
        case role
        case company
        case vCardData
        case photoAsset
        case expiresAt
        case createdAt
    }

    init(
        recordID: CKRecord.ID,
        displayName: String,
        role: String,
        company: String,
        vCardData: String,
        expiresAt: Date,
        createdAt: Date = .now
    ) {
        self.recordID = recordID
        self.displayName = displayName
        self.role = role
        self.company = company
        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.displayName = (record[Field.displayName.rawValue] as? String) ?? ""
        self.role = (record[Field.role.rawValue] as? String) ?? ""
        self.company = (record[Field.company.rawValue] as? String) ?? ""
        self.vCardData = vCardData
        self.expiresAt = expiresAt
        self.createdAt = (record[Field.createdAt.rawValue] as? Date) ?? record.creationDate ?? .now
    }

    func toCKRecord(photoAssetFileURL: URL? = nil) -> CKRecord {
        let record = CKRecord(recordType: Self.recordType, recordID: recordID)
        record[Field.displayName.rawValue] = displayName
        record[Field.role.rawValue] = role
        record[Field.company.rawValue] = company
        record[Field.vCardData.rawValue] = vCardData
        if let photoAssetFileURL {
            record[Field.photoAsset.rawValue] = CKAsset(fileURL: photoAssetFileURL)
        }
        record[Field.expiresAt.rawValue] = expiresAt
        record[Field.createdAt.rawValue] = createdAt
        return record
    }
}
