import Foundation

/// Service for creating temporary vCard files for sharing via AirDrop, Messages, etc.
/// These files include embedded profile photos, which are too large for QR codes.
struct VCardFileService {
    
    /// Creates a temporary .vcf file for the given card and returns its URL.
    /// The file includes the embedded profile photo if available.
    @MainActor
    func createVCardFile(for payloadProvider: some VCardPayloadProviding) throws -> URL {
        let payload = payloadProvider.vCardFilePayload
        
        // Create a sanitized filename from the card's name
        let sanitizedName = sanitizeFilename(payloadProvider.vCardName)
        let filename = sanitizedName.isEmpty ? "contact" : sanitizedName
        
        // Write to temp directory with .vcf extension
        let tempURL = URL.temporaryDirectory
            .appending(path: "\(filename).vcf")
        
        // Remove existing file if present
        try? FileManager.default.removeItem(at: tempURL)
        
        // Write the vCard data
        try payload.write(to: tempURL, atomically: true, encoding: .utf8)
        
        return tempURL
    }
    
    /// Cleans up a temporary vCard file after sharing is complete.
    func cleanupVCardFile(at url: URL) {
        try? FileManager.default.removeItem(at: url)
    }
    
    /// Sanitizes a string for use as a filename by removing invalid characters.
    private func sanitizeFilename(_ name: String) -> String {
        let invalidCharacters = CharacterSet(charactersIn: "/\\:*?\"<>|")
        return name
            .components(separatedBy: invalidCharacters)
            .joined()
            .trimmingCharacters(in: .whitespacesAndNewlines)
    }
}
