const { Sequelize } = require('sequelize'); require('dotenv').config(); // Configure database based on environment let sequelize; if (process.env.NODE_ENV === 'test') { // Use SQLite in-memory database for testing sequelize = new Sequelize({ dialect: 'sqlite', storage: ':memory:', logging: false }); } else { // Use PostgreSQL for production/development sequelize = new Sequelize( process.env.DB_NAME || 'drone_detection', process.env.DB_USER || 'postgres', process.env.DB_PASSWORD || 'password', { host: process.env.DB_HOST || 'localhost', port: process.env.DB_PORT || 5432, dialect: 'postgres', logging: process.env.NODE_ENV === 'development' ? console.log : false, pool: { max: 5, min: 0, acquire: 30000, idle: 10000 } } ); } // Import models const Device = require('./Device')(sequelize); const DroneDetection = require('./DroneDetection')(sequelize); const Heartbeat = require('./Heartbeat')(sequelize); const User = require('./User')(sequelize); const AlertRule = require('./AlertRule')(sequelize); const AlertLog = require('./AlertLog')(sequelize); const Tenant = require('./Tenant')(sequelize); const ManagementUser = require('./ManagementUser')(sequelize); // Define associations Device.hasMany(DroneDetection, { foreignKey: 'device_id', as: 'detections' }); DroneDetection.belongsTo(Device, { foreignKey: 'device_id', as: 'device' }); Device.hasMany(Heartbeat, { foreignKey: 'device_id', as: 'heartbeats' }); Heartbeat.belongsTo(Device, { foreignKey: 'device_id', as: 'device' }); User.hasMany(AlertRule, { foreignKey: 'user_id', as: 'alertRules' }); AlertRule.belongsTo(User, { foreignKey: 'user_id', as: 'user' }); AlertRule.hasMany(AlertLog, { foreignKey: 'alert_rule_id', as: 'logs' }); AlertLog.belongsTo(AlertRule, { foreignKey: 'alert_rule_id', as: 'rule' }); DroneDetection.hasMany(AlertLog, { foreignKey: 'detection_id', as: 'alerts' }); AlertLog.belongsTo(DroneDetection, { foreignKey: 'detection_id', as: 'detection' }); // Tenant associations Tenant.hasMany(User, { foreignKey: 'tenant_id', as: 'users' }); User.belongsTo(Tenant, { foreignKey: 'tenant_id', as: 'tenant' }); Tenant.hasMany(Device, { foreignKey: 'tenant_id', as: 'devices' }); Device.belongsTo(Tenant, { foreignKey: 'tenant_id', as: 'tenant' }); module.exports = { sequelize, Device, DroneDetection, Heartbeat, User, AlertRule, AlertLog, Tenant, ManagementUser };