module.exports = (sequelize, DataTypes) => {
  const WorkOrderOperationPlan = sequelize.define(
    'WorkOrderOperationPlan',
    {
      id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
      },
      work_order_id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        references: { model: 'WorkOrder', key: 'id' }
      },
      operation_sequence_no: {
        type: DataTypes.INTEGER,
        allowNull: false
      },
      operation_name: {
        type: DataTypes.STRING(500),
        allowNull: false
      },
      department_id: {
        type: DataTypes.INTEGER,
        allowNull: true,
        references: { model: 'Department', key: 'id' }
      },
      work_center_id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        references: { model: 'WorkCenter', key: 'id' }
      },
      machine_id: {
        type: DataTypes.INTEGER,
        allowNull: true,
        references: { model: 'Machine', key: 'id' }
      },
      planned_qty: {
        type: DataTypes.DECIMAL(18, 3),
        allowNull: false,
        defaultValue: 0
      },
      target_date: {
        type: DataTypes.DATEONLY,
        allowNull: true
      },
      standard_time_minutes: {
        type: DataTypes.INTEGER,
        allowNull: true
      },
      setup_time_minutes: {
        type: DataTypes.INTEGER,
        allowNull: true
      },
      status: {
        type: DataTypes.ENUM('PLANNED', 'RELEASED', 'IN_PROGRESS', 'COMPLETED', 'CLOSED'),
        allowNull: false,
        defaultValue: 'PLANNED'
      },
      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: 'work_order_operation_plan',
      indexes: [
        { fields: ['work_order_id'] },
        { fields: ['department_id'] },
        { fields: ['work_center_id'] },
        { fields: ['status'] },
        { unique: true, fields: ['work_order_id', 'operation_sequence_no'] }
      ]
    }
  );

  WorkOrderOperationPlan.associate = function (models) {
    WorkOrderOperationPlan.belongsTo(models.WorkOrder, { foreignKey: 'work_order_id', as: 'workOrder' });
    WorkOrderOperationPlan.belongsTo(models.Department, { foreignKey: 'department_id', as: 'department' });
    WorkOrderOperationPlan.belongsTo(models.WorkCenter, { foreignKey: 'work_center_id', as: 'workCenter' });
    WorkOrderOperationPlan.belongsTo(models.Machine, { foreignKey: 'machine_id', as: 'machine' });
    WorkOrderOperationPlan.belongsTo(models.User, { foreignKey: 'created_by', as: 'createdByUser' });
    WorkOrderOperationPlan.belongsTo(models.User, { foreignKey: 'updated_by', as: 'updatedByUser' });
  };

  return WorkOrderOperationPlan;
};

