import type { EntityManager } from '@mikro-orm/core';
import { PaymentMethod } from '../modules/payments/entities/payment-method.entity';
import type { Restaurant } from '../modules/restaurants/entities/restaurant.entity';
import { paymentMethodsData } from './data/payment-methods.data';

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

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

        if (!existing) {
          const paymentMethod = em.create(PaymentMethod, {
            restaurant,
            method: methodData.method,
            description: methodData.description,
            enabled: methodData.enabled,
            order: methodData.order,
            gateway: methodData.gateway,
            merchantId: methodData.merchantId,
          });
          em.persist(paymentMethod);
        } else {
          // Update existing payment method if needed
          if (
            existing.description !== methodData.description ||
            existing.enabled !== methodData.enabled ||
            existing.order !== methodData.order
          ) {
            existing.description = methodData.description;
            existing.enabled = methodData.enabled;
            existing.order = methodData.order;
            if (methodData.gateway !== undefined) {
              existing.gateway = methodData.gateway;
            }
            if (methodData.merchantId !== undefined) {
              existing.merchantId = methodData.merchantId;
            }
            em.persist(existing);
          }
        }
      }
    }

    await em.flush();
  }
}
