const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');

const Club = sequelize.define('Club', {
  id: {
    type: DataTypes.INTEGER.UNSIGNED,
    primaryKey: true,
    autoIncrement: true,
    comment: '클럽 고유 식별자'
  },
  name: {
    type: DataTypes.STRING,
    allowNull: false,
    comment: '클럽명'
  },
  description: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: '클럽 설명'
  },
  ownerId: {
    type: DataTypes.INTEGER.UNSIGNED,
    allowNull: false,
    references: {
      model: 'Users',
      key: 'id'
    },
    comment: '클럽장(소유자) 유저 ID'
  },
  location: {
    type: DataTypes.STRING,
    allowNull: true,
    comment: '주 활동 지역'
  },
  contact: {
    type: DataTypes.STRING,
    allowNull: true,
    comment: '연락처'
  },
  status: {
    type: DataTypes.ENUM('active', 'inactive', 'suspended'),
    allowNull: false,
    defaultValue: 'active',
    comment: '클럽 상태'
  },
  memberCount: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 0,
    comment: '회원 수'
  },
  femaleHandicap: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 15,
    comment: '여성 기본 핸디캡'
  },
  averageCalculationPeriod: {
    type: DataTypes.ENUM(
      '3month', 
      '6month', 
      '1year', 
      'firsthalf', 
      'secondhalf', 
      'quarterly', 
      'total'
    ),
    allowNull: false,
    defaultValue: '6month',
    comment: '에버리지 계산 기간'
  },
  createdAt: {
    type: DataTypes.DATE,
    allowNull: false,
    comment: '생성일'
  },
  updatedAt: {
    type: DataTypes.DATE,
    allowNull: false,
    comment: '수정일'
  }
}, {
  tableName: 'Clubs',
  comment: '볼링 클럽 정보를 저장하는 테이블',
  timestamps: true
});

Club.associate = (models) => {
  Club.hasMany(models.ClubFeature, { foreignKey: 'clubId' });
  Club.hasMany(models.ClubSubscription, { foreignKey: 'clubId' });
  Club.belongsTo(models.User, { foreignKey: 'ownerId', as: 'owner' });
  Club.belongsToMany(models.Feature, {
    through: models.ClubFeature,
    foreignKey: 'clubId',
  });
  Club.belongsToMany(models.SubscriptionPlan, {
    through: models.ClubSubscription,
    foreignKey: 'clubId',
    otherKey: 'planId',
  });
  Club.hasMany(models.ClubSubscription, { foreignKey: 'clubId' });
  Club.belongsToMany(models.Feature, {
    through: models.ClubFeature,
    foreignKey: 'clubId',
  });
  
  // Member와의 관계 추가
  Club.hasMany(models.Member, { foreignKey: 'clubId' });
};

module.exports = Club;
