import 'dotenv/config';
import 'reflect-metadata';
import { initializeDatabase } from '../infrastructure/persistence/data-source';
import { redisClient } from '../infrastructure/cache/redis-client';
import { createRepositories } from '../main/factories/repositories.factory';
import { createServices } from '../main/factories/services.factory';
import { createUseCases } from '../main/factories/use-cases.factory';
import {
  allNetworks,
  getNetworkAddressType,
  getNetworkExplorer,
  getNetworkThumbnail,
} from './networks.seed-data';

const run = async (): Promise<void> => {
  await initializeDatabase();

  const repositories = createRepositories();
  const services = createServices(redisClient);
  const useCases = createUseCases(repositories, services);

  let created = 0;
  let skipped = 0;

  for (const entry of allNetworks) {
    const existing = await repositories.networkRepository.findByName(entry.name);
    if (existing) {
      services.logger.info('Network already exists, skipping', { name: entry.name });
      skipped++;
      continue;
    }

    await useCases.createNetwork.execute({
      name: entry.name,
      code: entry.symbol,
      addressType: getNetworkAddressType(entry),
      thumbnail: getNetworkThumbnail(entry),
      explorer: getNetworkExplorer(entry),
      chainId: entry.chainId,
      status: 'active',
    });

    services.logger.info('Network created', { name: entry.name });
    created++;
  }

  services.logger.info('Network seeding complete', { created, skipped, total: allNetworks.length });
  await redisClient.quit();
  process.exit(0);
};

run().catch((error) => {
  // eslint-disable-next-line no-console
  console.error('Network seeding failed', error);
  process.exit(1);
});
