import 'reflect-metadata';
import { DataSource } from 'typeorm';
import { env } from '../../main/config/env';
import { DeviceEntity } from './entities/device.entity';
import { WalletEntity } from './entities/wallet.entity';
import { AddressEntity } from './entities/address.entity';
import { NetworkEntity } from './entities/network.entity';
import { TokenEntity } from './entities/token.entity';
import { TransactionEntity } from './entities/transaction.entity';

const isDevelopment = env.NODE_ENV === 'development';
const isTest = env.NODE_ENV === 'test';

export const AppDataSource = new DataSource({
  type: 'mysql',
  host: env.DB_HOST,
  port: env.DB_PORT,
  username: env.DB_USER,
  password: env.DB_PASS,
  database: env.DB_NAME,
  synchronize: isDevelopment || isTest,
  logging: isDevelopment ? ['error'] : false,
  entities: [DeviceEntity, WalletEntity, AddressEntity, NetworkEntity, TokenEntity, TransactionEntity],
  migrations: [`${__dirname}/migrations/*.ts`],
  subscribers: [],
});

export const initializeDatabase = async (): Promise<DataSource> => {
  if (AppDataSource.isInitialized) {
    return AppDataSource;
  }
  return AppDataSource.initialize();
};

export const runMigrations = async (): Promise<void> => {
  if (!AppDataSource.isInitialized) {
    await initializeDatabase();
  }
  await AppDataSource.runMigrations();
};

export const closeDatabase = async (): Promise<void> => {
  if (AppDataSource.isInitialized) {
    await AppDataSource.destroy();
  }
};
