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 { seedTokensForNetwork } from './seed-tokens.helper';

const networkId = process.argv[2];

if (!networkId) {
  // eslint-disable-next-line no-console
  console.error('Usage: npm run seed:network:tokens -- <network-id>');
  process.exit(1);
}

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

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

  const network = await repositories.networkRepository.findById(networkId);
  if (!network) {
    throw new Error(`Network not found: ${networkId}`);
  }

  services.logger.info('Seeding tokens for network', { network: network.name, id: network.id });

  const result = await seedTokensForNetwork(
    network,
    useCases,
    repositories.tokenRepository,
    services.coinMarketCapClient,
    services.logger,
  );

  services.logger.info('Network token seeding complete', {
    network: network.name,
    ...result,
  });

  await redisClient.quit();
  process.exit(0);
};

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