/**
 * Migration Script: Update items dengan code "AGR%" ke Item Group "POLARIS"
 * 
 * Jalankan dengan: node migrations/run_agr_to_polaris.js
 * 
 * Date: 2026-03-02
 */

const dbSAPPS = require("../apps/sapps/helpers/db");
const { Op } = require("sequelize");

async function main() {
  try {
    // Tunggu database siap
    console.log("⏳ Menunggu koneksi database...");
    await dbSAPPS.waitForInitialization();
    console.log("✅ Database connected!\n");

    // STEP 1: Cari item group POLARIS
    console.log("=== STEP 1: Mencari Item Group POLARIS ===");
    const polarisGroup = await dbSAPPS.ItemGroup.findOne({
      where: { display_name: "POLARIS" },
    });

    if (!polarisGroup) {
      console.error("❌ Item Group 'POLARIS' tidak ditemukan! Pastikan sudah dibuat terlebih dahulu.");
      process.exit(1);
    }
    console.log(`✅ Item Group POLARIS ditemukan: ID = ${polarisGroup.id}, Company ID = ${polarisGroup.company_id}\n`);

    // STEP 2: Cari semua item dengan code "AGR%"
    console.log("=== STEP 2: Mencari item dengan code AGR% ===");
    const agrItems = await dbSAPPS.Item.findAll({
      where: {
        code: { [Op.like]: "AGR%" },
      },
      include: [
        {
          model: dbSAPPS.ItemGroup,
          as: "itemgroups",
          attributes: ["id", "display_name"],
          required: false,
        },
      ],
      order: [["code", "ASC"]],
    });

    console.log(`📦 Total item ditemukan: ${agrItems.length}\n`);

    if (agrItems.length === 0) {
      console.log("⚠️  Tidak ada item dengan code dimulai AGR. Migration selesai.");
      process.exit(0);
    }

    // Preview items
    console.log("=== PREVIEW ITEM YANG AKAN DIUPDATE ===");
    console.log("-".repeat(90));
    console.log(
      "ID".padEnd(8) +
      "Code".padEnd(15) +
      "Display Name".padEnd(35) +
      "Current Group".padEnd(20) +
      "Group ID".padEnd(10)
    );
    console.log("-".repeat(90));

    let alreadyPolaris = 0;
    let needsUpdate = 0;

    agrItems.forEach((item) => {
      const currentGroup = item.itemgroups?.display_name || "(none)";
      const isPolaris = item.itemgroup_id === polarisGroup.id;

      if (isPolaris) alreadyPolaris++;
      else needsUpdate++;

      console.log(
        String(item.id).padEnd(8) +
        (item.code || "").padEnd(15) +
        (item.display_name || "").substring(0, 33).padEnd(35) +
        currentGroup.padEnd(20) +
        String(item.itemgroup_id || "-").padEnd(10) +
        (isPolaris ? "✅" : "🔄")
      );
    });

    console.log("-".repeat(90));
    console.log(`\n📊 Ringkasan:`);
    console.log(`   Total item AGR  : ${agrItems.length}`);
    console.log(`   Sudah POLARIS   : ${alreadyPolaris}`);
    console.log(`   Perlu diupdate  : ${needsUpdate}\n`);

    if (needsUpdate === 0) {
      console.log("✅ Semua item AGR sudah di group POLARIS. Tidak ada yang perlu diupdate.");
      process.exit(0);
    }

    // STEP 3: Update items
    console.log("=== STEP 3: Menjalankan UPDATE ===");
    const [updatedCount] = await dbSAPPS.Item.update(
      {
        itemgroup_id: polarisGroup.id,
        modified: new Date(),
        modified_by: 1,
      },
      {
        where: {
          code: { [Op.like]: "AGR%" },
          [Op.or]: [
            { itemgroup_id: { [Op.ne]: polarisGroup.id } },
            { itemgroup_id: null },
          ],
        },
      }
    );

    console.log(`✅ Berhasil update ${updatedCount} item ke group POLARIS!\n`);

    // STEP 4: Verifikasi
    console.log("=== STEP 4: VERIFIKASI ===");
    const verifyItems = await dbSAPPS.Item.findAll({
      where: { code: { [Op.like]: "AGR%" } },
      include: [
        {
          model: dbSAPPS.ItemGroup,
          as: "itemgroups",
          attributes: ["id", "display_name"],
          required: false,
        },
      ],
    });

    const allPolaris = verifyItems.every(
      (item) => item.itemgroup_id === polarisGroup.id
    );

    if (allPolaris) {
      console.log(`✅ VERIFIKASI BERHASIL: Semua ${verifyItems.length} item AGR sudah di group POLARIS`);
    } else {
      const nonPolaris = verifyItems.filter(
        (item) => item.itemgroup_id !== polarisGroup.id
      );
      console.error(
        `⚠️  VERIFIKASI GAGAL: ${nonPolaris.length} item belum di group POLARIS`
      );
      nonPolaris.forEach((item) => {
        console.error(`   - ${item.code}: group_id = ${item.itemgroup_id}`);
      });
    }

    console.log("\n🎉 Migration selesai!");
    process.exit(0);
  } catch (error) {
    console.error("❌ Error:", error.message);
    console.error(error);
    process.exit(1);
  }
}

main();
