import Foundation

struct SearchDataPayload: Decodable {
    let users: [UserSearchResult]
}

struct UserSearchResult: Decodable, Identifiable {
    let userId: UUID
//    let login: String
//    let fullName: String?
//    let customName: String?
//    let createdAt: Date?
    let profile: SearchProfile?

    var id: UUID { userId }
}

struct SearchProfile: Decodable {
    let userId: UUID
    let login: String
    let fullName: String?
    let customName: String?
    let bio: String?

    let isVerified: Bool
    let isSystem: Bool
    
    let lastSeen: Int?
    let createdAt: Date?
}

extension UserSearchResult {
    var preferredCustomName: String? {
        trimmed(profile?.customName)
    }

    var officialFullName: String? {
        trimmed(profile?.fullName)
    }

    var login: String? {
        trimmed(profile?.login)
    }

    var loginHandle: String {
        if let login {
            return "@\(login)"
        }
        return "@\(userId.uuidString)"
    }

    var displayName: String {
        if let official = officialFullName {
            return official
        }
        if let custom = preferredCustomName {
            return custom
        }
        if let login = login {
            return "@\(login)"
        }
        return "@\(userId.uuidString)"
    }

    var avatarInitial: String {
        let source = preferredCustomName
            ?? officialFullName
            ?? login
            ?? userId.uuidString

        if let character = source.first(where: { !$0.isWhitespace && $0 != "@" }) {
            return String(character).uppercased()
        }
        return "?"
    }

    var isOfficial: Bool {
        profile?.isVerified ?? false
    }

    var createdAt: Date? {
        profile?.createdAt
    }

    private func trimmed(_ value: String?) -> String? {
        guard let value = value?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty else {
            return nil
        }
        return value
    }
}
