import Foundation
import SwiftData

/* Only used for in app notifications */

public struct MiniProfileV2: Equatable, Hashable, Codable {
    public enum ProfileType: String, Equatable, Hashable, Codable {
        case user
        case system
        case group
    }

    public var profileTypeValue: String?
    public var profileType: ProfileType {
        guard let profileTypeValue else { return .system }
        return ProfileType(rawValue: profileTypeValue) ?? .system
    }

    public var displayName: String?
    public var handle: String?
    public var avatarImageURL: String?
    public var isFollowing: Bool

    init(_ remote: Components.Schemas.MiniProfileV2) throws {
        /* Has the _ in front of it because `type` is basically a reserved word */
        self.profileTypeValue = remote._type
        self.displayName = remote.display_name ?? ""
        self.handle = remote.handle
        self.avatarImageURL = remote.avatar_image_url
        self.isFollowing = remote.is_following ?? false
    }

    // Define coding keys for properties
    enum CodingKeys: String, CodingKey {
        case profileTypeValue = "profile_type_value"
        case displayName = "display_name"
        case handle
        case avatarImageURL = "avatar_image_url"
        case isFollowing = "is_following"
    }

    // Custom initializer for decoding
    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        profileTypeValue = try container.decodeIfPresent(String.self, forKey: .profileTypeValue)
        displayName = try container.decodeIfPresent(String.self, forKey: .displayName)
        handle = try container.decodeIfPresent(String.self, forKey: .handle)
        avatarImageURL = try container.decodeIfPresent(String.self, forKey: .avatarImageURL)
        isFollowing = try container.decode(Bool.self, forKey: .isFollowing)
    }

    // Encoder function for encoding
    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(profileTypeValue, forKey: .profileTypeValue)
        try container.encode(displayName, forKey: .displayName)
        try container.encode(handle, forKey: .handle)
        try container.encode(avatarImageURL, forKey: .avatarImageURL)
        try container.encode(isFollowing, forKey: .isFollowing)
    }
}
