import type { EntityManager } from '@mikro-orm/core';
import { User } from '../modules/users/entities/user.entity';
import { UserAddress } from '../modules/users/entities/user-address.entity';
import { usersData } from './data/users.data';
import { userAddressesData } from './data/user-addresses.data';
import { normalizePhone } from '../modules/utils/phone.util';

export class UsersSeeder {
  async run(em: EntityManager): Promise<Map<string, User>> {
    const usersMap = new Map<string, User>();

    // Create users
    for (const userData of usersData) {
      const normalizedPhone = normalizePhone(userData.phone);
      let user = await em.findOne(User, { phone: normalizedPhone });
      if (!user) {
        user = em.create(User, {
          phone: normalizedPhone, // Use normalized phone
          firstName: userData.firstName,
          lastName: userData.lastName,
          birthDate: new Date(userData.birthDate),
          marriageDate: new Date(userData.marriageDate),
          isActive: userData.isActive,
          gender: userData.gender,
        });
        em.persist(user);
      }
      usersMap.set(normalizedPhone, user); // Use normalized phone as key
    }

    await em.flush();

    // Create addresses for users
    for (const addressData of userAddressesData) {
      const normalizedPhone = normalizePhone(addressData.userPhone);
      const user = usersMap.get(normalizedPhone);
      if (!user) continue;

      // Check if address already exists for this user
      const existingAddress = await em.findOne(UserAddress, {
        user: { id: user.id },
        title: addressData.title,
        address: addressData.address,
      });

      if (!existingAddress) {
        // If setting as default, unset other default addresses for this user
        if (addressData.isDefault) {
          const existingDefaultAddresses = await em.find(UserAddress, {
            user: { id: user.id },
            isDefault: true,
          });
          for (const defaultAddress of existingDefaultAddresses) {
            defaultAddress.isDefault = false;
            em.persist(defaultAddress);
          }
        }

        const address = em.create(UserAddress, {
          user,
          title: addressData.title,
          address: addressData.address,
          city: addressData.city,
          province: addressData.province,
          postalCode: addressData.postalCode,
          latitude: addressData.latitude,
          longitude: addressData.longitude,
          phone: addressData.phone,
          isDefault: addressData.isDefault,
        });
        em.persist(address);
      }
    }

    await em.flush();
    return usersMap;
  }
}
