const connectDB = require("./config/db");

(async () => {
    await connectDB();

    const User = require("./model/User");
    const Car = require("./model/Car");
    const ServiceRecord = require("./model/ServiceRecord");
    const Payment = require("./model/Payment");

    const chief = await User.findOne({ username: "chief" }).lean();
    if (!chief) {
        console.error("chief user not found");
        process.exit(1);
    }

    const userId = chief._id;

    const r1 = await Car.updateMany(
        { userId: { $exists: false } },
        { $set: { userId } }
    );

    const r2 = await ServiceRecord.updateMany(
        { userId: { $exists: false } },
        { $set: { userId } }
    );

    const r3 = await Payment.updateMany(
        { userId: { $exists: false } },
        { $set: { userId } }
    );

    console.log("backfill done", {
        car: r1.modifiedCount ?? r1.nModified,
        serviceRecord: r2.modifiedCount ?? r2.nModified,
        payment: r3.modifiedCount ?? r3.nModified,
    });

    process.exit(0);
})().catch((e) => {
    console.error(e);
    process.exit(1);
});

