import type { EntityManager } from '@mikro-orm/core';
import { Coupon } from '../modules/coupons/entities/coupon.entity';
import type { Restaurant } from '../modules/restaurants/entities/restaurant.entity';
import { couponsData } from './data/coupons.data';

export class CouponsSeeder {
  async run(em: EntityManager, restaurantsMap: Map<string, Restaurant>): Promise<void> {
    for (const couponData of couponsData) {
      const restaurant = restaurantsMap.get(couponData.restaurantSlug);

      if (!restaurant) continue;

      const existing = await em.findOne(Coupon, {
        code: couponData.code,
        restaurant: { id: restaurant.id },
      });

      if (!existing) {
        const coupon = em.create(Coupon, {
          restaurant,
          code: couponData.code,
          name: couponData.name,
          description: couponData.description,
          type: couponData.type,
          value: couponData.value,
          maxDiscount: couponData.maxDiscount,
          minOrderAmount: couponData.minOrderAmount,
          maxUses: couponData.maxUses,
          maxUsesPerUser: couponData.maxUsesPerUser,
          startDate: couponData.startDate ? new Date(couponData.startDate) : undefined,
          endDate: couponData.endDate ? new Date(couponData.endDate) : undefined,
          isActive: couponData.isActive,
          usedCount: 0,
        });

        em.persist(coupon);
      }
    }

    await em.flush();
  }
}
