import mongoConnection from "$connections/mongo/mongo.connection.js";
import models from "$models/index.js";

const DEFAULT_OWNER_NATIONAL_ID = "0019431171";

const CLUB_REWARD_TEMPLATES = [
  {
    pointsCost: 10000,
    amount: 500000,
    fundSeoRegisterNo: "11343",
    fundName: "صندوق درآمد ثابت امید",
    expiresInDays: 90,
  },
  {
    pointsCost: 30000,
    amount: 1000000,
    fundSeoRegisterNo: "11383",
    fundName: "صندوق سهامی امید",
    expiresInDays: 120,
  },
  {
    pointsCost: 60000,
    amount: 2000000,
    fundSeoRegisterNo: "11141",
    fundName: "صندوق مختلط امید",
    expiresInDays: 150,
  },
];

const parseArgs = (argv = process.argv.slice(2)) => {
  const options = {
    ownerNationalId: DEFAULT_OWNER_NATIONAL_ID,
    ownerUserId: "",
  };

  argv.forEach((arg) => {
    const [flag, ...rawParts] = arg.split("=");
    const rawValue = rawParts.join("=");

    if (!rawValue) {
      return;
    }

    if (flag === "--owner-national-id") {
      options.ownerNationalId = rawValue;
      return;
    }

    if (flag === "--owner-user-id") {
      options.ownerUserId = rawValue;
    }
  });

  return options;
};

const addDays = (baseDate, days) => {
  const result = new Date(baseDate);
  result.setDate(result.getDate() + days);
  return result;
};

const resolveOwnerUser = async ({ ownerUserId, ownerNationalId }) => {
  if (ownerUserId) {
    const user = await models.user.findById(ownerUserId).select("_id fullName");
    if (!user) {
      throw new Error(`Owner user was not found for id: ${ownerUserId}`);
    }

    return user;
  }

  const user = await models.user
    .findOne({ nationalId: ownerNationalId })
    .select("_id fullName nationalId");

  if (!user) {
    throw new Error(
      `Owner user was not found for nationalId: ${ownerNationalId}`,
    );
  }

  return user;
};

const findExistingReward = async (template) => {
  return models.clubReward
    .findOne({
      pointsCost: template.pointsCost,
      status: "active",
    })
    .populate({
      path: "paymentBatch",
      match: {
        usageContext: "club_reward",
        amount: template.amount,
        fundSeoRegisterNo: template.fundSeoRegisterNo,
        fundName: template.fundName,
      },
    });
};

const seedClubRewards = async ({ ownerUserId }) => {
  console.log("🎁 Seeding default club rewards...");

  const createdRewards = [];
  const skippedRewards = [];

  for (const template of CLUB_REWARD_TEMPLATES) {
    const existingReward = await findExistingReward(template);

    if (existingReward?.paymentBatch) {
      skippedRewards.push(template);
      continue;
    }

    const expiresAt = addDays(new Date(), template.expiresInDays);
    const paymentBatch = await models.paymentBatchCard.create({
      title: `جایزه باشگاه - ${template.fundName}`,
      description: "قالب پیش‌فرض کارت هدیه برای باشگاه مشتریان",
      createMode: "single",
      usageContext: "club_reward",
      quantity: 1,
      amount: template.amount,
      fundSeoRegisterNo: template.fundSeoRegisterNo,
      fundName: template.fundName,
      totalAmount: template.amount,
      status: "active",
      user: ownerUserId,
      expiresAt,
    });

    const reward = await models.clubReward.create({
      pointsCost: template.pointsCost,
      status: "active",
      rewardType: "payment_card",
      paymentBatch: paymentBatch._id,
    });

    createdRewards.push(reward);
  }

  console.log(`✅ Created ${createdRewards.length} club rewards`);
  console.log(`⏭️  Skipped ${skippedRewards.length} existing club rewards`);

  return {
    createdRewards,
    skippedRewards,
  };
};

async function run() {
  const options = parseArgs();

  return new Promise((resolve, reject) => {
    mongoConnection.once("open", async () => {
      try {
        console.log("✅ Connected to database successfully");
        const ownerUser = await resolveOwnerUser(options);
        console.log(
          `👤 Reward owner resolved: ${ownerUser.fullName || ownerUser._id}`,
        );

        const result = await seedClubRewards({ ownerUserId: ownerUser._id });

        console.log("✨ Club reward seeding finished");
        console.log(
          `📊 Summary: created=${result.createdRewards.length}, skipped=${result.skippedRewards.length}`,
        );

        process.exit(0);
      } catch (error) {
        console.error("❌ Club reward seeding failed:", error);
        process.exit(1);
      }
    });

    mongoConnection.once("error", (error) => {
      console.error("❌ Database connection error:", error);
      process.exit(1);
    });
  });
}

run();
