import User from "../DB/Model/user.model.js";
import Chat from "../DB/Model/chat.modal.js";

export async function getNearbyUsers(userId, radiusInMiles = 10) {
    const user = await User.findById(userId).select("city");
    if (!user || !user.city) {
        return [];
    }

    const nearbyUsers = await User.find({
        city: user.city,
        _id: { $ne: userId },
    }).select("_id full_name email city");

    return nearbyUsers;
}

export async function handleNearbyGroup(userId, radiusInMiles = 10) {
    const nearbyUsers = await getNearbyUsers(userId, radiusInMiles);

    if (!nearbyUsers.length) {
        return null;
    }

    const participants = [userId, ...nearbyUsers.map((u) => u._id)];
    let existingGroup = await Chat.findOne({
        chatType: "group",
        city: nearbyUsers[0].city,
        participants: { $all: participants, $size: participants.length },
    });

    if (existingGroup) {
        return existingGroup;
    }

    // create new group
    const newGroup = await Chat.create({
        participants,
        chatType: "group",
        city: nearbyUsers[0].city,
    });

    return newGroup;
}
