module.exports = (sequelize, DataTypes) => {
  const FiscalYear = sequelize.define('FiscalYear', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    company_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'Company',
        key: 'id'
      }
    },
    fiscal_year: {
      type: DataTypes.STRING(9),
      allowNull: false,
      comment: 'Format: YYYY-YYYY (e.g., 2024-2025)'
    },
    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('ACTIVE', 'INACTIVE', 'CLOSED'),
      allowNull: false,
      defaultValue: 'ACTIVE'
    },
    created_by: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'User',
        key: 'id'
      }
    },
    updated_by: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'User',
        key: 'id'
      }
    }
  }, {
    tableName: 'fiscal_year',
    indexes: [
      {
        unique: true,
        fields: ['company_id', 'fiscal_year']
      },
      {
        fields: ['start_date', 'end_date']
      },
      {
        fields: ['status']
      }
    ]
  });

  FiscalYear.associate = function(models) {
    FiscalYear.belongsTo(models.Company, { foreignKey: 'company_id', as: 'company' });
    FiscalYear.belongsTo(models.User, { foreignKey: 'closed_by', as: 'closedByUser' });
    FiscalYear.hasMany(models.FiscalPeriod, { foreignKey: 'fiscal_year_id', as: 'periods' });
  };

  return FiscalYear;
};

