module.exports = (sequelize, DataTypes) => {
  const Machine = sequelize.define('Machine', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    company_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'Company',
        key: 'id'
      },
      comment: 'Company this machine belongs to'
    },
    plant_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'Plant',
        key: 'id'
      },
      comment: 'Plant location (optional)'
    },
    machine_code: {
      type: DataTypes.STRING(50),
      allowNull: false,
      comment: 'Machine code (e.g., LSR 01, PBR 02)'
    },
    machine_description: {
      type: DataTypes.STRING(200),
      allowNull: false,
      comment: 'Machine description/name'
    },
    specification: {
      type: DataTypes.STRING(500),
      allowNull: true,
      comment: 'Machine specifications'
    },
    make: {
      type: DataTypes.STRING(100),
      allowNull: true,
      comment: 'Machine manufacturer/make'
    },
    installed_on: {
      type: DataTypes.INTEGER,
      allowNull: true,
      comment: 'Year when machine was installed'
    },
    history_card_no: {
      type: DataTypes.STRING(50),
      allowNull: true,
      comment: 'History card number (e.g., HC-07)'
    },
    location: {
      type: DataTypes.STRING(100),
      allowNull: true,
      comment: 'Location/Plant name (e.g., SARA INDUSTRIES, RAM INDUSTRIES)'
    },
    status: {
      type: DataTypes.ENUM('WORKING', 'NOT_WORKING', 'MAINTENANCE', 'INACTIVE'),
      allowNull: false,
      defaultValue: 'WORKING',
      comment: 'Machine status'
    },
    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: 'machine',
    indexes: [
      {
        unique: true,
        fields: ['company_id', 'machine_code']
      },
      {
        fields: ['company_id']
      },
      {
        fields: ['plant_id']
      },
      {
        fields: ['status']
      },
      {
        fields: ['location']
      }
    ]
  });

  Machine.associate = function(models) {
    Machine.belongsTo(models.Company, { foreignKey: 'company_id', as: 'company' });
    Machine.belongsTo(models.Plant, { foreignKey: 'plant_id', as: 'plant' });
    Machine.belongsTo(models.User, { foreignKey: 'created_by', as: 'createdByUser' });
    Machine.belongsTo(models.User, { foreignKey: 'updated_by', as: 'updatedByUser' });
  };

  return Machine;
};

