import type { EntityManager } from '@mikro-orm/core';
import { Delivery } from '../modules/delivery/entities/delivery.entity';
import type { Restaurant } from '../modules/restaurants/entities/restaurant.entity';
import { deliveryMethodsData } from './data/delivery-methods.data';
import { DeliveryFeeTypeEnum } from 'src/modules/delivery/interface/delivery';

export class DeliveryMethodsSeeder {
  async run(em: EntityManager, restaurants: Restaurant[]): Promise<void> {
    for (const restaurant of restaurants) {
      if (!restaurant) continue;

      for (const methodData of deliveryMethodsData) {
        const existing = await em.findOne(Delivery, {
          restaurant: { id: restaurant.id },
          method: methodData.method,
        });

        if (!existing) {
          const delivery = em.create(Delivery, {
            restaurant,
            method: methodData.method,
            description: methodData.description,
            deliveryFee: methodData.deliveryFee,
            minOrderPrice: methodData.minOrderPrice,
            enabled: methodData.enabled,
            order: methodData.order,
            deliveryFeeType: DeliveryFeeTypeEnum.FIXED,
            perKilometerFee: null,
            distanceBasedMinCost: null,
          });
          em.persist(delivery);
        } else {
          // Update existing delivery method if needed
          if (
            existing.description !== methodData.description ||
            existing.deliveryFee !== methodData.deliveryFee ||
            existing.minOrderPrice !== methodData.minOrderPrice ||
            existing.order !== methodData.order
          ) {
            existing.description = methodData.description;
            existing.deliveryFee = methodData.deliveryFee;
            existing.minOrderPrice = methodData.minOrderPrice;
            existing.order = methodData.order;
            em.persist(existing);
          }
        }
      }
    }

    await em.flush();
  }
}
