import ComposableArchitecture
import Foundation

// MARK: - Analytics Context

public struct HookAnalyticsContext: Codable {
    public var recommendationItemId: String?
    public let contextType: String
    public let contextId: String?
    public let sourceUrl: String?
    public var clipId: String?
    public var authorHandle: String?
    public var profileUserId: String?
    public var targetUserId: String?
    public var isUserObjectOwner: Bool?

    public init(
        recommendationItemId: String?,
        contextType: String,
        contextId: String?,
        sourceUrl: String? = nil,
        clipId: String? = nil,
        authorHandle: String? = nil,
        profileUserId: String? = nil,
        targetUserId: String? = nil,
        isUserObjectOwner: Bool? = nil
    ) {
        self.recommendationItemId = recommendationItemId
        self.contextType = contextType
        self.contextId = contextId
        self.sourceUrl = sourceUrl
        self.clipId = clipId
        self.authorHandle = authorHandle
        self.profileUserId = profileUserId
        self.targetUserId = targetUserId
        self.isUserObjectOwner = isUserObjectOwner
    }

    public func toJsonString() -> String {
        guard let data = try? JSONEncoder().encode(self),
              let jsonString = String(data: data, encoding: .utf8)
        else {
            return "{}"
        }
        return jsonString
    }
}

public extension Hook {
    func analyticsContext(
        contextType: String?,
        contextId: String?,
        sourceUrl: String? = nil,
        targetUserId: String? = nil,
        isUserObjectOwner: Bool? = nil
    ) -> HookAnalyticsContext {
        return HookAnalyticsContext(
            recommendationItemId: self.recommendationItemId,
            contextType: HookAnalyticsContext.mapContextType(contextType),
            contextId: contextId,
            sourceUrl: sourceUrl,
            targetUserId: targetUserId,
            isUserObjectOwner: isUserObjectOwner
        )
    }
}

public extension HookAnalyticsContext {
    static func mapContextType(_ originalType: String?) -> String {
        guard let originalType = originalType else { return "Unknown" }

        switch originalType.lowercased() {
        case "hooks_feed":
            return "hooks_feed"
        case "profile":
            return "Profile"
        case "library":
            return "Library"
        case "profilegrid":
            return "ProfileGrid"
        case "librarygrid":
            return "LibraryGrid"
        case "hook":
            return "Hook"
        case "notification":
            return "Notification"
        case "clip":
            return "Clip"
        default:
            return "Unknown"
        }
    }
}
