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

import Country from '@/modules/master/location/country/country.model';
import State from '@/modules/master/location/state/state.model';
import City from '@/modules/master/location/city/city.model';

export const seedLocationData = async ({
  superAdminId,
}: {
  superAdminId: string | Types.ObjectId;
}) => {
  try {
    const countryCount = await Country.countDocuments();

    if (countryCount === 0) {
      const jsonPath = path.join(
        process.cwd(),
        'src/shared/seeder/location/india_states_cities.json',
      );

      const data = JSON.parse(fs.readFileSync(jsonPath, 'utf-8')) as any;

      if (data) {
        const countryDoc = await Country.create({
          name: String(data.name).toLowerCase(),
          code: String(data.code),
          loc: {
            type: 'Point',
            coordinates: [Number(data.longitude), Number(data.latitude)],
          },
          createdBy: superAdminId,
          updatedBy: superAdminId,
        });

        const allStates = Array.isArray(data.states) ? data.states : [];

        const statesPayload = allStates.map((st: any) => ({
          name: String(st.name).toLowerCase(),
          code: st.code ? String(st.code).toLowerCase() : undefined,
          country: countryDoc._id,
          loc: {
            type: 'Point',
            coordinates: [
              Number(st.longitude || 0),
              Number(st.latitude || 0),
            ],
          },
          createdBy: superAdminId,
          updatedBy: superAdminId,
        }));

        const stateDocs = await State.insertMany(statesPayload, {
          ordered: false,
        });

        const stateNameToId = new Map<string, any>();
        stateDocs.forEach((doc: any) =>
          stateNameToId.set(String(doc.name).toLowerCase(), doc._id),
        );

        const citiesPayload: any[] = [];

        allStates.forEach((st: any) => {
          const stateId = stateNameToId.get(String(st.name).toLowerCase());
          if (!stateId) return;

          (Array.isArray(st.cities) ? st.cities : []).forEach((ct: any) => {
            citiesPayload.push({
              name: String(ct.name).toLowerCase(),
              state: stateId,
              loc: {
                type: 'Point',
                coordinates: [
                  Number(ct.longitude || 0),
                  Number(ct.latitude || 0),
                ],
              },
              createdBy: superAdminId,
              updatedBy: superAdminId,
            });
          });
        });

        if (citiesPayload.length > 0) {
          await City.insertMany(citiesPayload, { ordered: false });
        }

        console.log('✅ Location seeding completed successfully');
      }
    }
  } catch (err) {
    console.log('❌ Error in seeding location data', err);
  }
};
