module.exports = (sequelize, DataTypes) => {
  const FiscalPeriod = sequelize.define('FiscalPeriod', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    fiscal_year_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'FiscalYear',
        key: 'id'
      }
    },
    period_number: {
      type: DataTypes.INTEGER,
      allowNull: false,
      comment: 'Period number (1-12 for monthly periods)'
    },
    period_code: {
      type: DataTypes.STRING(10),
      allowNull: false,
      comment: 'Period code (e.g., P01, P02)'
    },
    period_name: {
      type: DataTypes.STRING(50),
      allowNull: false,
      comment: 'Period name (e.g., April 2024)'
    },
    start_date: {
      type: DataTypes.DATEONLY,
      allowNull: false
    },
    end_date: {
      type: DataTypes.DATEONLY,
      allowNull: false
    },
    is_closed: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false
    },
    closed_date: {
      type: DataTypes.DATEONLY,
      allowNull: true
    },
    closed_by: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'User',
        key: 'id'
      }
    },
    status: {
      type: DataTypes.ENUM('OPEN', 'CLOSED', 'LOCKED'),
      allowNull: false,
      defaultValue: 'OPEN'
    }
  }, {
    tableName: 'fiscal_period',
    indexes: [
      {
        unique: true,
        fields: ['fiscal_year_id', 'period_number']
      },
      {
        fields: ['start_date', 'end_date']
      },
      {
        fields: ['status']
      }
    ]
  });

  FiscalPeriod.associate = function(models) {
    FiscalPeriod.belongsTo(models.FiscalYear, { foreignKey: 'fiscal_year_id', as: 'fiscalYear' });
    FiscalPeriod.belongsTo(models.User, { foreignKey: 'closed_by', as: 'closedByUser' });
  };

  return FiscalPeriod;
};

