const { sequelize } = require('../config/database');
const { Op } = require('sequelize');
const User = require('./User');
const Club = require('./Club');
const Event = require('./Event');
const EventTeam = require('./EventTeam');
const EventParticipant = require('./EventParticipant');
const EventScore = require('./EventScore');
const Member = require('./Member');
const Notification = require('./Notification');
const Feature = require('./Feature');
const ClubFeature = require('./ClubFeature');
const Menu = require('./Menu');
const SubscriptionPlan = require('./SubscriptionPlan');
const SubscriptionPlanFeature = require('./SubscriptionPlanFeature');
const ClubSubscription = require('./ClubSubscription');
const ActivityLog = require('./activityLog');
const EventTeamMember = require('./EventTeamMember');
const PaymentRequest = require('./PaymentRequest');
const AverageCache = require('./AverageCache');

// 모델 동기화 함수
const syncModels = async () => {
  try {
    // 외래 키 제약 조건을 비활성화하고 테이블 재생성
    // 개발
    // await sequelize.query('SET FOREIGN_KEY_CHECKS = 0');
    // await sequelize.sync({ force: true });
    // await sequelize.query('SET FOREIGN_KEY_CHECKS = 1');
    
    // 운영 alter: true - 구조변경만 alter처리
    // await sequelize.sync({ alter: true });
    await sequelize.sync();
  } catch (error) {
    console.error('모델 동기화 중 오류 발생:', error);
  }
};

// 모든 모델의 associate 호출 (관계 자동 연결)
const db = {
  User,
  Club,
  Event,
  EventTeam,
  EventParticipant,
  EventScore,
  Member,
  Notification,
  Feature,
  ClubFeature,
  Menu,
  SubscriptionPlan,
  SubscriptionPlanFeature,
  ClubSubscription,
  AverageCache,
  ActivityLog,
  EventTeamMember,
  PaymentRequest,
};
Object.values(db).forEach(model => {
  if (model.associate) model.associate(db);
});

module.exports = {
  sequelize,
  User,
  Club,
  Event,
  EventTeam,
  EventParticipant,
  EventScore,
  Member,
  Notification,
  Feature,
  ClubFeature,
  Menu,
  SubscriptionPlan,
  SubscriptionPlanFeature,
  ClubSubscription,
  ActivityLog,
  EventTeamMember,
  PaymentRequest,
  AverageCache,
  syncModels
};
