import type { EntityManager } from '@mikro-orm/core';
import { Food } from '../modules/foods/entities/food.entity';
import type { Restaurant } from '../modules/restaurants/entities/restaurant.entity';
import type { Category } from '../modules/foods/entities/category.entity';
import { MealType } from '../modules/foods/interface/food.interface';
import { foodsData } from './data/foods.data';

export class FoodsSeeder {
  async run(
    em: EntityManager,
    restaurantsMap: Map<string, Restaurant>,
    categoriesMap: Map<string, Category>,
  ): Promise<void> {
    for (const foodData of foodsData) {
      const restaurant = restaurantsMap.get(foodData.restaurantSlug);
      const key = `${foodData.restaurantSlug}-${foodData.categoryTitle}`;

      const normalize = (s: string) => (s || '').replace(/\s+/g, ' ').trim();

      let category = categoriesMap.get(key);

      // Fallback: try to find category by normalized title if exact key not found
      if (!category) {
        for (const [k, v] of categoriesMap.entries()) {
          const parts = k.split('-');
          const kSlug = parts[0];
          const kTitle = parts.slice(1).join('-');
          if (kSlug === foodData.restaurantSlug && normalize(kTitle) === normalize(foodData.categoryTitle)) {
            category = v;
            break;
          }
        }
      }

      if (!restaurant || !category) {
        console.warn(
          `Skipping food \"${foodData.title}\" — missing ${!restaurant ? 'restaurant' : 'category'} for key ${key}`,
        );
        continue;
      }

      const existing = await em.findOne(Food, {
        title: foodData.title,
        restaurant,
      });

      if (!existing) {
        const food = em.create(Food, {
          title: foodData.title,
          desc: foodData.desc,
          content: foodData.content,
          price: foodData.price,
          restaurant,
          category,
          isActive: foodData.isActive,
          // new fields on Food entity
          weekDays: foodData.weekDays ?? [0, 1, 2, 3, 4, 5, 6],
          mealTypes: foodData.mealTypes ?? [MealType.BREAKFAST, MealType.LUNCH, MealType.DINNER, MealType.SNACK],
          discount: foodData.discount ?? 0,
          score: foodData.score ?? 0,
          inPlaceServe: true,
          pickupServe: true,
          images: foodData.images,
          isSpecialOffer: foodData.isSpecialOffer ?? false,
        });

        em.persist(food);
      }
    }

    await em.flush();
  }
}
