import Foundation

/// State for managing App Clip card sharing.
/// Handles upload to CloudKit and provides the resulting App Clip URL.
@MainActor
@Observable
final class AppClipShareState {
    private let service: SharedCardProviding

    var isUploading = false
    var uploadResult: SharedCardUploadResult?
    var errorMessage: String?

    /// Returns true if an App Clip URL has been generated.
    var hasAppClipURL: Bool { uploadResult != nil }

    init(service: SharedCardProviding = SharedCardCloudKitService()) {
        self.service = service
    }

    /// Uploads a card to CloudKit for App Clip sharing.
    /// - Parameter card: The business card to share.
    func shareViaAppClip(card: BusinessCard) async {
        isUploading = true
        errorMessage = nil
        uploadResult = nil

        defer { isUploading = false }

        do {
            uploadResult = try await service.uploadSharedCard(card)
        } catch {
            errorMessage = error.localizedDescription
        }
    }

    /// Resets the state for a new share operation.
    func reset() {
        uploadResult = nil
        errorMessage = nil
    }
}
