/* eslint-disable no-console */

import fs from 'fs';
import path from 'path';
import { Types } from 'mongoose';

import { MasterBank } from '@/modules/master/bank/bank.model';
import { getObjectId } from '@/shared/utils/commonHelper';

function normalizeBankName(raw: string) {
  return String(raw || '')
    .replace(/\s+/g, ' ')
    .trim();
}

export const seedMasterBanksFromCsv = async ({
  superAdminId,
}: {
  superAdminId: string | Types.ObjectId;
}) => {
  const superAdminObjectId = getObjectId(superAdminId as any);
  const csvPath = path.join(process.cwd(), 'src/shared/seeder/banks/banks.csv');

  if (!fs.existsSync(csvPath)) {
    console.warn(`⚠️ banks.csv not found at: ${csvPath}`);
    return;
  }

  const file = fs.readFileSync(csvPath, 'utf-8');
  const lines = file
    .split(/\r?\n/)
    .map((l) => normalizeBankName(l))
    .filter(Boolean);

  if (!lines.length) {
    console.warn('⚠️ banks.csv is empty');
    return;
  }

  const uniqueByLower = new Map<string, string>();
  for (const name of lines) {
    const lower = name.toLowerCase();
    if (!uniqueByLower.has(lower)) uniqueByLower.set(lower, name);
  }

  const ops = Array.from(uniqueByLower.entries()).map(([nameLower, name]) => ({
    updateOne: {
      filter: { nameLower },
      update: {
        $set: {
          name,
          nameLower,
          updatedBy: superAdminObjectId,
        },
        $setOnInsert: {
          createdBy: superAdminObjectId,
        },
      },
      upsert: true,
    },
  }));

  console.log(`➡️ Seeding master banks: ${ops.length} unique names`);

  // chunk to avoid large bulk payloads
  const chunkSize = 1000;
  for (let i = 0; i < ops.length; i += chunkSize) {
    const chunk = ops.slice(i, i + chunkSize);
    await MasterBank.bulkWrite(chunk as any, { ordered: false });
  }

  console.log('✅ Master banks seeded/updated successfully');
};
