module.exports = (sequelize, DataTypes) => {
  const Attendance = sequelize.define('Attendance', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    company_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'Company',
        key: 'id'
      }
    },
    plant_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'Plant',
        key: 'id'
      }
    },
    employee_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'Employee',
        key: 'id'
      }
    },
    attendance_date: {
      type: DataTypes.DATEONLY,
      allowNull: false
    },
    shift_code: {
      type: DataTypes.STRING(50),
      allowNull: true
    },
    in_time: {
      type: DataTypes.TIME,
      allowNull: true
    },
    out_time: {
      type: DataTypes.TIME,
      allowNull: true
    },
    work_hours: {
      type: DataTypes.DECIMAL(5, 2),
      allowNull: true,
      defaultValue: 0
    },
    overtime_hours: {
      type: DataTypes.DECIMAL(5, 2),
      allowNull: true,
      defaultValue: 0
    },
    attendance_status: {
      type: DataTypes.ENUM('PRESENT', 'ABSENT', 'HALF_DAY', 'LEAVE', 'HOLIDAY', 'WEEK_OFF', 'LATE', 'EARLY_OUT'),
      allowNull: false,
      defaultValue: 'PRESENT'
    },
    leave_type: {
      type: DataTypes.STRING(50),
      allowNull: true
    },
    remarks: {
      type: DataTypes.TEXT,
      allowNull: true
    },
    is_manual_entry: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: true
    },
    essl_device_id: {
      type: DataTypes.STRING(100),
      allowNull: true
    },
    status: {
      type: DataTypes.ENUM('DRAFT', 'SUBMITTED', 'APPROVED', 'LOCKED'),
      allowNull: false,
      defaultValue: 'DRAFT'
    }
  }, {
    tableName: 'attendance',
    indexes: [
      {
        fields: ['company_id']
      },
      {
        fields: ['plant_id']
      },
      {
        fields: ['employee_id']
      },
      {
        fields: ['attendance_date']
      },
      {
        unique: true,
        fields: ['employee_id', 'attendance_date']
      }
    ]
  });

  Attendance.associate = function(models) {
    Attendance.belongsTo(models.Company, { foreignKey: 'company_id', as: 'company' });
    Attendance.belongsTo(models.Plant, { foreignKey: 'plant_id', as: 'plant' });
    Attendance.belongsTo(models.Employee, { foreignKey: 'employee_id', as: 'employee' });
  };

  return Attendance;
};

