// Migration to fix offering and lookingFor field structure
// Run this once to convert string values to object structure
import mongoose from "mongoose";
import Member from "../models/member.js";
import { connectDB } from "../utils/mongoose.js";

async function migrateOfferingLookingFor() {
  await connectDB();

  console.log("Starting migration: fixing offering and lookingFor structure...");

  try {
    // Find all members where offering or lookingFor is a string (not an object)
    const members = await Member.find({
      $or: [
        { offering: { $type: "string" } },
        { lookingFor: { $type: "string" } },
      ],
    });

    console.log(`Found ${members.length} members to migrate`);

    for (const member of members) {
      const updates = {};

      // Convert offering if it's a string
      if (typeof member.offering === "string") {
        updates.offering = {
          text: member.offering,
          tags: [],
        };
        console.log(
          `Converting offering for member ${member._id}: "${member.offering}"`,
        );
      }

      // Convert lookingFor if it's a string
      if (typeof member.lookingFor === "string") {
        updates.lookingFor = {
          text: member.lookingFor,
          tags: [],
        };
        console.log(
          `Converting lookingFor for member ${member._id}: "${member.lookingFor}"`,
        );
      }

      // Update the member
      if (Object.keys(updates).length > 0) {
        await Member.findByIdAndUpdate(member._id, { $set: updates });
      }
    }

    console.log("Migration completed successfully!");
    process.exit(0);
  } catch (error) {
    console.error("Migration failed:", error);
    process.exit(1);
  }
}

migrateOfferingLookingFor();
