// FILE: backend/src/db/sequelize.js
// “lazy-load” ตาม env ปลอดภัยกว่า และยังคง dbReady() ให้เรียกทดสอบได้
// ใช้ได้เมื่อจำเป็น (เช่น งาน admin tool เฉพาะกิจ)
// ตั้ง ENABLE_SEQUELIZE=1 เพื่อเปิดใช้ Model loader; ไม่งั้นจะเป็นโหมดเบา ๆ
import { Sequelize } from "sequelize";
import { config } from "../config.js";

export const sequelize = new Sequelize(
  config.DB.NAME,
  config.DB.USER,
  config.DB.PASS,
  {
    host: config.DB.HOST,
    port: config.DB.PORT,
    dialect: "mariadb",
    logging: false,
    dialectOptions: { timezone: "Z" },
    define: { freezeTableName: true, underscored: false, timestamps: false },
    pool: { max: 10, min: 0, idle: 10000 },
  }
);

export let User = null;
export let Role = null;
export let Permission = null;
export let UserRole = null;
export let RolePermission = null;

if (process.env.ENABLE_SEQUELIZE === "1") {
  // โหลดโมเดลแบบ on-demand เพื่อลดความเสี่ยง runtime หากไฟล์โมเดลไม่มี
  const mdlUser = await import("./models/User.js").catch(() => null);
  const mdlRole = await import("./models/Role.js").catch(() => null);
  const mdlPerm = await import("./models/Permission.js").catch(() => null);
  const mdlUR = await import("./models/UserRole.js").catch(() => null);
  const mdlRP = await import("./models/RolePermission.js").catch(() => null);

  if (mdlUser?.default) User = mdlUser.default(sequelize);
  if (mdlRole?.default) Role = mdlRole.default(sequelize);
  if (mdlPerm?.default) Permission = mdlPerm.default(sequelize);
  if (mdlUR?.default) UserRole = mdlUR.default(sequelize);
  if (mdlRP?.default) RolePermission = mdlRP.default(sequelize);

  if (User && Role && Permission && UserRole && RolePermission) {
    User.belongsToMany(Role, {
      through: UserRole,
      foreignKey: "user_id",
      otherKey: "role_id",
    });
    Role.belongsToMany(User, {
      through: UserRole,
      foreignKey: "role_id",
      otherKey: "user_id",
    });

    Role.belongsToMany(Permission, {
      through: RolePermission,
      foreignKey: "role_id",
      otherKey: "permission_id",
    });
    Permission.belongsToMany(Role, {
      through: RolePermission,
      foreignKey: "permission_id",
      otherKey: "role_id",
    });
  }
}

export async function dbReady() {
  // โหมดเบา ๆ: แค่ทดสอบเชื่อมต่อ
  await sequelize.authenticate();
}
