import Foundation

/// Content type mapping and attachment path security
public enum ContentTypeMapping {
    public static func contentType(forExtension ext: String) -> String {
        switch ext.lowercased() {
        case "jpg", "jpeg": return "image/jpeg"
        case "png": return "image/png"
        case "gif": return "image/gif"
        case "heic", "heif": return "image/heic"
        case "webp": return "image/webp"
        case "mp4": return "video/mp4"
        case "mov": return "video/quicktime"
        case "mp3": return "audio/mpeg"
        case "m4a": return "audio/mp4"
        case "pdf": return "application/pdf"
        default: return "application/octet-stream"
        }
    }

    /// Check if an attachment path is within ~/Library/Messages/Attachments.
    /// Only this directory is allowed — prevents path traversal.
    public static func isAllowedAttachmentPath(_ path: String, homeDirectory: String) -> Bool {
        guard !path.isEmpty else { return false }

        let expandedPath: String
        if path.hasPrefix("~/") {
            expandedPath = homeDirectory + String(path.dropFirst(1))
        } else {
            expandedPath = path
        }

        let allowedPrefix = homeDirectory.hasSuffix("/")
            ? homeDirectory + "Library/Messages/Attachments"
            : homeDirectory + "/Library/Messages/Attachments"

        guard !expandedPath.contains("..") else { return false }

        return expandedPath.hasPrefix(allowedPrefix)
    }
}
