import { Types, Model } from "mongoose";

type ObjectIdLike = Types.ObjectId | string;

interface CleanRefArrayParams {
    parentModel: Model<any>;
    refModel: Model<any>;
    parentId: ObjectIdLike;
    fieldName: string;
}

export async function cleanRefArrayField({ parentModel, refModel, parentId, fieldName }: CleanRefArrayParams): Promise<{ keptIds: Types.ObjectId[]; removedIds: Types.ObjectId[] }> {
    const parent = await parentModel.findById(parentId).lean();
    if (!parent) { throw new Error("Parent document not found") }
    const rawIds: ObjectIdLike[] = parent[fieldName] || [];
    if (!Array.isArray(rawIds) || rawIds.length === 0) { return { keptIds: [], removedIds: [] } }
    const ids = rawIds.map((id) => typeof id === "string" ? new Types.ObjectId(id) : id);
    const existing = await refModel.find({ _id: { $in: ids } }).select("_id").lean();
    const existingSet = new Set(existing.map((d) => String(d._id)));
    const keptIds = ids.filter((id) => existingSet.has(String(id)));
    const removedIds = ids.filter((id) => !existingSet.has(String(id)));
    await parentModel.updateOne({ _id: parentId }, { $set: { [fieldName]: keptIds } });
    return { keptIds, removedIds };
}
