import { ModuleParams } from "@erp/core";
import { logger } from "../logger";

const allModelInitializers: any[] = [];
const registeredModels: { [key: string]: any } = {};

/**
 * 🔹 Registra todos los modelos en Sequelize
 */
export const registerModels = (models: any[], params?: ModuleParams) => {
  allModelInitializers.push(...models);
};

export const initModels = async (params: ModuleParams) => {
  logger.info("Init models...", { label: "initModels" });

  const { database } = params;
  if (!database) {
    const error = new Error("❌ Database not found.");
    logger.error(error.message, {
      label: "initModels",
    });
    throw error;
  }

  // Inicializar modelos
  for (const initializer of allModelInitializers) {
    const model = initializer(database);
    registeredModels[model.name] = model;
    logger.info(`🔸 Model "${model.name}" registered (sequelize)`, { label: "registerModel" });
  }

  // Configurar asociaciones
  for (const model of Object.values(registeredModels)) {
    if (typeof model.associate === "function") {
      model.associate(database);
    }
  }

  try {
    // Sincronizamos DB en modo desarrollo
    if (process.env.NODE_ENV !== "production") {
      await database.sync({ force: false, alter: true });
      logger.info(`✔️${"  "}Database synchronized successfully.`, { label: "initModels" });
    } else {
      logger.warn("⚠️ Running in production mode - Skipping database sync.", {
        label: "initModels",
      });
    }
  } catch (err) {
    const error = err as Error;
    logger.error("❌ Error synchronizing database:", { error, label: "initModels" });
    throw error;
  }
};
