import { createConnection } from "typeorm";
import { runSeeder } from 'typeorm-seeding';
import consola from 'consola';
import { config } from '../config';
import { ConfigFlag } from '../models/entities/ConfigFlags';
import SeedPublicOrg from '../seeds/SeedPublicOrg';
import SeedTestRunners from '../seeds/SeedTestRunners';
import SeedUsers from '../seeds/SeedUsers';
/**
 * Loader for the database that creates the database connection and initializes the database tabels.
 * It also triggers the seeding process if no users got detected in the database.
 */
export default async () => {
    const connection = await createConnection();
    
    // Log discovered entities for debugging
    consola.info(`TypeORM discovered ${connection.entityMetadatas.length} entities:`);
    consola.info(connection.entityMetadatas.map(m => m.name).sort().join(', '));
    
    await connection.synchronize();

    //The data seeding part
    if (!(await connection.getRepository(ConfigFlag).findOne({ option: "seeded:user", value: "true" }))) {
        await runSeeder(SeedUsers);
        await connection.getRepository(ConfigFlag).save({ option: "seeded:user", value: "true" });
    }
    if (!(await connection.getRepository(ConfigFlag).findOne({ option: "seeded:citizenorg", value: "true" }))) {
        await runSeeder(SeedPublicOrg);
        await connection.getRepository(ConfigFlag).save({ option: "seeded:citizenorg", value: "true" });
    }
    if (!(await connection.getRepository(ConfigFlag).findOne({ option: "seeded:testdata", value: "true" })) && config.seedTestData == true) {
        await runSeeder(SeedTestRunners);
        await connection.getRepository(ConfigFlag).save({ option: "seeded:testdata", value: "true" });
    }

    return connection;
};