/* eslint-disable no-console */

import { Types } from 'mongoose';

import { ICompany } from '@/modules/company/company.interface';
import { Company } from '@/modules/company/company.model';
import User from '@/modules/user/user.model';
import { IUserDoc } from '@/modules/user/user.interfaces';
import {
  MemberType,
  Status,
  CompanyType,
  UserType,
  CommonTypes,
} from '@/shared/constants/enum.constant';
import { getObjectId } from '@/shared/utils/commonHelper';
import { addOrUpdatePermission } from '@/modules/permissions/permissions.service';
import { SUPERADMIN_SEED_PERMISSIONS } from '@/modules/permissions/permissions.constant';
import { updateRole } from '@/modules/roles/roles.service';
import { seedSuperadminTemplates } from '@/modules/communication/whatsapp/whatsapp.helper';
import { Whatsapp } from '@/modules/communication/whatsapp/whatsapp.model';
import { storeFast2smsTemplates } from './fast2sms/addTemplate';
import { seedLeadStage } from './leadStage';
import { seedLocationData } from './location/seedLocationData';
import { seedAndhraPradeshUnified } from './location/Andhra Pradesh/seedAndhraPradeshUnified';
import { importAreas } from './area';
import { seedMasterBanksFromCsv } from './banks/seedBanks';

export const createSuperAdminUser = async (): Promise<boolean> => {
  try {
    const name = CommonTypes.SUPERADMIN;
    const companyPayload: Partial<ICompany> = {
      name,
      companyType: CompanyType.SUPERADMIN,
    };

    const superAdminCompany = (await Company.findOneAndUpdate(
      { name: companyPayload.name },
      { $setOnInsert: companyPayload },
      { new: true, upsert: true },
    ))!;

    console.info('✅ Super Admin company ensured');

    const superAdminRole = await updateRole({
      name: `${name}`,
      description: `Role with all permissions for ${name} Role`,
      company: superAdminCompany._id as Types.ObjectId,
    });

    console.info('✅ Super Admin role ensured');

    await addOrUpdatePermission(
      superAdminCompany._id as Types.ObjectId,
      superAdminRole._id as Types.ObjectId,
      SUPERADMIN_SEED_PERMISSIONS.map((group) => ({
        group: group.group,
        groupAccess: group.groupAccess,
        permissions: group.permissions,
        createdBy: null,
        updatedBy: null,
      })),
    );

    console.info('✅ Super Admin permissions assigned');

    const userPayload: Partial<IUserDoc> = {
      firstName: 'SuperAdmin',
      lastName: 'Makanify',
      phone: {
        dialCode: 91,
        number: 1234567891,
      },
      email: 'hello@makanify.com',
      password: 'Makanify@123',
      isEmailVerified: true,
      status: Status.ACTIVE,
      memberType: MemberType.INTERNAL,
      userType: UserType.SUPERADMIN,
      company: {
        id: getObjectId(superAdminCompany._id as any),
        role: [superAdminRole._id as Types.ObjectId],
      },
    };

    let superAdminUser: IUserDoc;

    const existingSuperAdminUser = await User.findOne({
      email: userPayload.email,
    });

    if (existingSuperAdminUser) {
      console.info('✅ Super Admin user already exists');
      superAdminUser = existingSuperAdminUser;
    } else {
      console.info('➡️ Creating Super Admin user...');
      superAdminUser = await User.create(userPayload);
    }

    console.info('✅ Super Admin user ensured');

    // Seed Lead Stages

    await seedLeadStage({
      superAdminId: superAdminUser._id as Types.ObjectId,
    });

    console.log('✅ Lead Stages seeded');

    console.info('➡️ Importing locations...');
    await seedLocationData({
      superAdminId: superAdminUser._id as Types.ObjectId,
    });

    await importAreas({
      superAdminId: superAdminUser._id as Types.ObjectId,
    });
    console.info('✅ Areas imported successfully.');

    console.info('➡️ Seeding Andhra Pradesh locations (cities and areas)...');
    await seedAndhraPradeshUnified({
      superAdminId: superAdminUser._id as Types.ObjectId,
    });
    console.info('✅ Andhra Pradesh locations (cities and areas) seeded successfully.');

    console.info('✅ Locations imported successfully.');

    console.info('➡️ Seeding Andhra Pradesh locations (cities and areas)...');
    await seedAndhraPradeshUnified({
      superAdminId: superAdminUser._id as Types.ObjectId,
    });
    console.info('✅ Andhra Pradesh locations (cities and areas) seeded successfully.');

    await seedMasterBanksFromCsv({
      superAdminId: superAdminUser._id as Types.ObjectId,
    });

    // await syncWhatsappTemplates(
    //   Whatsapp,
    //   Company,
    //   superAdminCompany._id as Types.ObjectId,
    //   WhatsappResponseCodes.WHATSAPP_ERROR,
    // );

    const whatsappTemplates = await seedSuperadminTemplates(
      Whatsapp,
      superAdminCompany._id as Types.ObjectId,
    );

    if (!whatsappTemplates) console.error('❌ Whatsapp templates not synced');
    else console.info('✅ Whatsapp templates synced');

    await storeFast2smsTemplates(superAdminCompany._id as Types.ObjectId);
    console.info('✅ Fast2sms templates synced');

    // NOTE: can add if needed for superadmin also

    // await syncEmailTemplates(
    //   superAdminCompany._id as Types.ObjectId,
    //   true,
    // );

    // console.info('✅ Email templates synced');

    console.info('✅ Super Admin registration completed successfully.');
    return true;
  } catch (error) {
    console.error('❌ Error in creating/updating Super Admin:', error);
    return null;
  }
};
